call apply bind

作者:知乎用户
链接:https://www.zhihu.com/question/20289071/answer/80892838
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

关于call()方法中的this

https://segmentfault.com/q/1010000005721719

obj.call(thisObj, arg1, arg2, ...);
obj.apply(thisObj, [arg1, arg2, ...]);
两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和方法。或者说thisObj『继承』了obj的属性和方法。唯一区别是apply接受的是数组参数,call接受的是连续参数。

使用call apply后,call()的第一个参数thisObj将继承obj的方法和属性。

例子:

// function add(j, k){
//     return j+k;
// }

// function sub(j, k){
//     return j-k;
// }
// console.log(add.call(sub, 5, 3)); //8


var Parent = function(){
    this.name = "yjc";
    this.age = 22;
}

var child = {};

console.log(child);//Object {} ,空对象

Parent.call(child);
console.log(child.name); //Object {name: "yjc", age: 22}

使用构造函数继承:
/**

  • 实现 Student 构造函数,接受 name, grade 参数,并且通过借用构造函数继承 PersonStudent 创建的实例满足下列条件:
    1. 具有 namegrade 实例属性,分别等于输入的参数。
    1. 具有 selfIntroduce 原型方法,调用会输出(console.log)字符串 My name is ${name}. I am Grade ${grade}, 其中 namegrade 分别对应相应的属性值,
    1. student instanceof Student结果是 true, student instanceof Person 结果是 false。;
      */
/**
 * Person 构造函数
 */
function Person(name,grade) {
    this.name = name;
    this.grade = grade;
}
Person.prototype.sayHello = function() {
    console.log('Hi! I am ' + this.name);
}

// TODOS: 实现 Student
function Student(name,grade){
    Person.call(this,name,grade);
   // this.grade = grade;
}
Student.prototype.selfIntroduce = function(){
    console.log("My name is " + this.name + ". I am Grade " + this.grade);
} 

你可能感兴趣的:(call apply bind)