[TOC]
## 1.原型链
JavaScript 规定,所有对象都有自己的原型对象(prototype)。一方面,任何一个对象,都可以充当其他对象的原型
所有对象皆有__proto__属性,它指向它的原型对象
## 2.继承
如何改变this关键字的指向call,apply,bind
1.函数作为普通函数调用,this指向window
~~~
function show(){
console.log(this);
}
show(); //window
~~~
~~~
var name = "cheng"
function show(){
console.log(this.name);
}
show();
~~~
### Call
~~~
var name = "cheng"
function show(){
console.log(this.name);
}
var zhang = {
name:"张三"
}
show.call(zhang);
~~~
### Apply
~~~
var name = "cheng"
function show(){
console.log(this.name);
}
var zhang = {
name:"张三"
}
show.apply(zhang);
~~~
Call和apply之间的区别
如果要传递参数,apply跟数组
eg:
~~~
function show(a,b){
console.log(this.name);
console.log(a+b)
}
var zhang = {
name:"张三"
}
//show.call(zhang,1,2)
show.apply(zhang,[1,2]);
~~~
### Bind
bind后函数不会执行,而只是返回一个改变了上下文的函数副本,而call和apply是直接执行函数
## demo01
~~~
<div id="text">div</div>
<button id="btn">btn</button>
var id = "world"
var btn = document.getElementById("btn");
var text = document.getElementById("text");
btn.onclick = function(){
console.log(this.id); //world
}.bind(this);
~~~
## demo02
~~~
var name = "li";
var cheng = {
name:"cheng"
}
var test = function(){
console.log(this.name)
}.bind(cheng);
test();
~~~
## demo03定时器
Eg:在函数内部的定时器中
~~~
<div id="text">div</div>
<button id="btn">btn</button>
<script>
var id = "world"
var btn = document.getElementById("btn");
var text = document.getElementById("text");
btn.onclick = function(){
setTimeout(function(){
console.log(this.id); //world
},1000)
}
</script>
~~~
## 解决方案01 bind
~~~
<div id="text">div</div>
<button id="btn">btn</button>
<script>
var id = "world"
var btn = document.getElementById("btn");
var text = document.getElementById("text");
btn.onclick = function(){
setTimeout(function(){
console.log(this.id);
}.bind(this),1000)
}
</script>
~~~
## 解决方案 02 self
~~~
var id = "world"
var btn = document.getElementById("btn");
var text = document.getElementById("text");
btn.onclick = function(){
var self = this;
setTimeout(function(){
console.log(self.id);
},1000)
}
~~~
## 解决方案 03 箭头函数
~~~
<button id="btn">btn</button>
<script>
var id = "world"
var btn = document.getElementById("btn");
var text = document.getElementById("text");
btn.onclick = function(){
setTimeout(()=>{
console.log(this.id)
},1000)
}
</script>
~~~
## 3.继承实现
~~~
var Person = function(name,age){
this.name = name;
this.age = age;
}
Person.prototype.see = function(){
console.log(this.name+"爱看片")
}
function Teacher(name,age){
Person.call(this,name,age);
}
Teacher.prototype = new Person();
var cheng = new Teacher("cheng",20);
cheng.see();
~~~