一.call() 和 apply()用法
这两个方法,之前确实没有使用过,看起来貌似以后会为我省点代码,直接做个demo 吧。
1.
function Animail(){
this.name="动物";
this.showName = function(){
alert(this.name);
};
}
function Cat(){
this.name = "猫咪";
}
var animail = new Animail();
var cat = new Cat();
animail.showName.call(cat);
打印效果:
2. 具体applay 和 call 作用一样,只是语法不一样
function myFunction(a,b,c){
this.a = a;
this.b = b;
this.c = c;
}
var obj = new Object();
alert(obj.a); // undefined
myFunction.apply(obj,[2,5,8]);
//myFunction.call(obj,2,5,8);
alert(obj.a);//2
二. prototype
function Animail(){}
Animail.prototype.name = "动物";
Animail.prototype.age = 2;
Animail.prototype.type = "001";
function Cat(){
this.name = "猫咪";
this.age = 3;
}
Cat.prototype = Animail.prototype;
var animail = new Animail();
var cat = new Cat();
alert(cat.name); // cat 自己的name:猫咪
alert(cat.age); //cat 自己的age:3
alert(cat.type); //Animail的type:2