JS中的this指向与继承
在js中call和apply的用法与this有着千丝万缕的联系,在需要实现继承时往往会让初学者比较头疼,本篇写的是最基础的继承与this指向
this的指向
-
构造函数创建 :输出
per.show() alert(per.name)
此时构造函数内的this指向=> per => “KID”function Person(){ this.name = "KID"; } Person.prototype.show =function(){ alert(this.name) } var per = new Person(); per.show(); alert(per.name);
-
事件绑定: 发生了函数赋值 此时的this指向改变成了btn 点击
按钮
输出 undefinedthis永远指向当前函数的主人
在绑定了按钮后 this的主人也会发生改变function Person(){ this.name = "KID"; //(假设绑定了一个id为“btn”的按钮) document.getElementById("btn").onclick = this.show; } Person.prototype.show =function(){ alert(this.name); } var per = new Person(); per.show(); alert(per.name); //解决办法 function Person(){ this.name = "KID"; //绑定前拿到this var _this =this; //(假设绑定了一个id为“btn”的按钮) document.getElementById("btn").onclick = _this.show; }
-
定时器的事件绑定 此时定时器里的函数是系统调用的 this的指向为window this再次发生了改变
function Person(){ this.name = "KID"; //启动定时器输出this.show setInterval(this.show,3000); } Person.prototype.show =function(){ alert(this.name); } var per = new Person(); per.show(); alert(per.name); //解决方法 function Person(){ this.name = "KID"; //提前拿到当前this var _this = this; //启动定时器输出this.show setInterval(_this.show,3000);
总结: this的指向永远是函数当前的主人 在我们需要调用函数又不想改变this指向时 需要提前声明变量拿到当前的this
4. 函数属性的继承(构造函数的伪装)
//示例
function Parent (name,sex){
this.name = name;
this.sex = sex;
}
//添加原型方法
parent.prototype.show = function(){
alert("姓名" + this.name + "性别" + this.sex)
}
//声明函数继承 Parent的函数 并添加自己的函数
function Worker(name,sex,job){
//通过call方法改变Parent的this指向
Parent.call(this,name,sex)
this.job = job;
}
//此时wk里既有Parent的函数属性 又有了Worker函数的属性
var wk = new Worker("小明","男","程序员")
alert(wk.name);
alert(wk.sex);
alert(wk.job);
//Worker里没并没有 tihs.name属性 但通过继承得到了这个属性 所以可通过浏览器打印
- 函数方法的继承 (原型链)通过遍历的方法把Parent的prototype方法获取到
for(var func in Parent.prototype){ Worker.prototype[func] = Parent.prototype[func]; }
对于 apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。例如,有一个函数定义如下:
var func = function(arg1, arg2) {
};
就可以通过如下方式来调用:
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])