call/apply用法

call/apply

作用,改变this指向
区别,后面传的参数形式不同

function Person(name, age){
   this.name = name;
   this.age = age;
}
 var person = new Person('deng',100);
var  obj = {
}
Person.call(obj,  'cheng',  300);
这里的call相当于将this对象发生改变 转成obj  也
就是call的第一个参数 然后obj有了所有的属性
//test()  --> test.call ();
function Person(name,  age,  sex){
       this.name  =  name;
       this.age  =  age;
       this.sex  =  sex;
}
function  Student(name,  age,  sex,  tel,  grade){
    /var  this = {name :"", age : "", sex:  ""}
    Person.call(this,  name,  age,  sex);
    this.tel  =  tel;
    this.grade  =  grade;
}
var  student  =  new  Student('sunny',  123,  
'male',  139, 2017 )
function Wheel(wheelSize,  style){
        this.style  =  style;
        this.wheelSize  =  wheelSize;
}
function  Sit(c,  sitColor){
        this.c  =  c;
        this.sitColor  =  sitColor;
}
function Model(height,  width,  len){
        this.height  =  height;
        this.width  =  width;
        this.len  =  len;
}
function Car(wheelSize,  style,  c,  sitColor,  
height,  width,  len){
        Wheel.call(this,wheelSize,  style)          
        Sit.call(this, c,  sitColor)
        Model.call(this, height,  width,  len)
}
var car = new Car(100,  "花里胡哨的",  '真皮',  
'red',  1800,  1900,  4900);

call 需要把实参按照形参的个数传进去
apply 需要传一个arguments
Wheel.apply(this,[wheelSize, style]);
Sit.apply(this, [c, sitColor]);
Model.apply(this, [height, width, len]);

你可能感兴趣的:(call/apply用法)