JavaScript中apply()方法的使用

每个函数都包含两个非继承而来的方法,apply()和call()。这两个方法的区别只是接受的参数不同。

apply接受两次参数,一个 是运行函数的作用域,另一个是参数数组(既可以是Array的实例也可以是argument对象),call的第一个参数和apply一致,变化的是其余的参数都要直接传给参数。如:a.apply(this,[1,2,3])=a.call(this,1,2,3)

apply的主要用途是改变函数的作用域,在特定的作用域中调用函数,实际上等于设置函数体内的this对象的值。

apply可以用于实现类似其他语言中的继承和多重继承

使用示例

function a(x){
    return this.name=x;
}
function b(y){
    return a.apply(this,arguments);
}
alert(b("1234"));  //1234

实现继承

function a(name){
  this.name = name;
  this.showName = function(){
        alert(this.name);    
    }    
}

function b(name){
  a.apply(this,[name]);    
}

var B= new b("1234");
B.showName();   //1234
var Person = function(name,age){
    this.name = name;
    this.age = age;
};

var Student = function(name,age,height){
    Person.apply(this,arguments);
    this.height = height;
};

var XiaoMing = new Student("xiaoming",18,170);
console.log(XiaoMing)  //Student {name: "xiaoming", age: 18, height: 170}

猜你喜欢

转载自blog.csdn.net/qq_42265289/article/details/81149388