JavaScript call / apply 学习

  • 谁调用 this就指向谁
Person.prototype = {
    name: 'a',
    sayName: function () {
        console.log(this.name);
    }
}

function Person() {
    this.name = 'b';
}

var person = new Person();

console.log(person.sayName()); // 输出 ‘b’ 因为是Person调用的

console.log(person.prototype.sayName()); // 输出 ‘a’
  • call / apply

        功能:改变this指向 默认this指向window

        区别: call 需要把实参按照形参的个数穿进去

                     apply 需要传一个arguments 数组

//function test(){}

// test.call(); // 相当于 test()

function Person(name, age) {
    this.name = name;
    this.age = age
}

var person = new Person('xiaoming', 18);

var obj = {
    
}

Person.call(obj, 'xiaozhang', 20); // 借用别人工厂创建自己要的功能对象

console.log(obj); // {name: 'xiaozhang', age: 20}
  • 练习call
function Person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

function Student(name, age, sex, tel, grade) {
    // 借用Person构造函数来实现功能 不需要重复写两遍
    // 相当于 var this = {name: name, age: age, sex: sex}
    Person.call(this, name, age, sex);
    this.tel = tel;
    this.grade = grade;
}

var student = new Student('sunny', 18, 'male', 135, 2018);
  • 练习2
function Wheel(size, style) {
    this.size = size;
    this.style = style;
}

function Sit(c, color) {
    this.c = c;
    this.color = color;
}

function Model(h, w, l) {
    this.h = h;
    this.w = w;
    this.l = l;
}

function Car(size, style, c, color, h, w, l) {
    // Wheel.apply(this, [size, style]);
    Wheel.call(this, size, style);
    // Sit.apply(this, [c, color]);
    Sit.call(this, c, color);
    // Model.apply(this, [h, w, l]);
    Model.call(this, h, w, l);
}

var car = new Car(100, 'cool', '真皮', 'red', 4900, 2800, 5300);

猜你喜欢

转载自blog.csdn.net/fanlixing6/article/details/85082684