您的位置:首页 > 移动开发

JS中Apply和Call的用法

2018-01-03 14:10 423 查看
/*

Apply和Call使用方法

(1)函数层面

obj.apply(obj1, arguments)

obj.call(obj1, argument1, argument2, ...)

这两个函数都是使用obj对象来替换obj1来执行对应的函数

这个可用于对象的继承

例如:

function add(a, b){
console.log(a+b);

}

function sub(a, b){
console.log(a-b);

}

add.call(sub, a, b); //使用add函数来替代sub进行a和b的运算

add.apply(sub, [a, b]);

*/

function add(a, b){
console.log(a+b);

}

function sub(a, b){
console.log(a-b);

}

add.call(sub, 2, 1);

add.apply(sub, [2, 1]);

//(2)对象继承方面

function Person(name, age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log("hello");
}

}

function Print(){
this.funcName = "Print";
this.show = function(){
var msg = [];
for (var key in this){
if (typeof(this[key]) != "function"){
msg.push([key, ":", this[key]].join(""));
}
}
console.log(msg.join(" "));
};

}

function Student(name, age, grade, school){
//Person.apply(this, arguments);
//Print.apply(this, arguments);
Person.call(this, name, age);
Print.call(this);
this.grade = grade;
this.school = school;

}

var p1 = new Person("jake", 10);

p1.sayHello();

var s1 = new Student("tom", 13, 6, "kidgarden");

s1.show();

s1.sayHello();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: