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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值