var A = function(name){
this.name = name;
}
var B = function(){
A.apply(this, arguments);
//apply传入对象时我知道this指向这个对象,请问apply(this)是什么意思呢?
}
B.prototype.getName = function(){
return this.name;
}
var b = new B("2B铅笔");
console.log( b.getName() ); // 输出: 2B铅笔
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
A.apply(this, arguments);就是调用A函数,调用的时候以this为A构造器里的this,以调用B函数的参数为调用A函数的参数,就相当于A.call(this,'2B铅笔'),所以生成的b对象有个name属性是2B铅笔。
需要绑定context(上下文)。apply、call一般用来修改context的,即this的指向。A.apply(this,arguments),其实将函数A中的this绑定在B上,即此时this是指向B的。