继续
call完成继续
用于完成函数继续,call的第二个参数可所以恣意范例
function Animal(){
this.name = "";
this.say = function(){
console.log("hello");
}
}
function dog(){
this.name = "xiao";
//把Animal的要领应用到dog这个对象身上
Animal.call(this);
}
console.log(new dog()); // dog { name: '', say: [Function] }
apply完成继续
用于完成函数继续,apply的第二个参数必需是数组,也可所以arguments
function Animal(){
this.name = "";
this.say = function(){
console.log("hello");
}
}
function dog(){
this.name = "xiao";
//把Animal的要领应用到dog这个对象身上
Animal.apply(this,arguments);
}
console.log(new dog()); // dog { name: '', say: [Function] }
继续的优化
假如组织函数this绑定太多属性,在实例化后会形成糟蹋,为此我们平常会运用原型链来优化,然则运用原型链以后我们的apply和call的继续要领就会失效,因而我们平常运用夹杂的写法。
让子的原型链指向父的实例(父实例化的对象)
dog.prototype = new Animal();
让父的属性创建在子的this上
Animal.call(this)
function Animal(name){
this.name = name;
this.say = function(){
console.log("hello");
}
}
Animal.prototype.action = function() {
console.log("running");
}
function dog(name,type){
this.name = name;
//把Animal的要领应用到dog这个对象身上
Animal.call(this,type);
}
dog.prototype = new Animal();
console.log(new dog('xiao', 'gold')); // Animal { name: 'gold', say: [Function] }
(new dog('xiao')).action() //running
apply 通报一个数组或arguments,而call就要一个个地传过
案例
es5中的继续
function Reactangle(length,width) {
this.length = length;
this.width = width;
}
Reactangle.prototype.getArea = function(){
return this.length * this.width;
}
function Square(length) {
Reactangle.call(this.length,length);
}
Square.prototype = Object.create(Reactangle.prototype,{
constructor: {
value:Square,
enumerable:true,
writeable:true,
configurable:true
}
});
var square = new Square(3);
console.log(square.getArea());
console.log(square instanceof Square);
console.log(square instanceof Reactangle);
在es6中完成继续
class Reactangle {
constructor(length,width) {
this.length = length;
this.width = width;
}
getArea() {
return this.length * this.width;
}
}
class Square extends Reactangle {
constructor(length) {
// 等价于 Reactangle.call(this.length,length)
super(length,length);
}
}
var square = new Square(3);
console.log(square.getArea()); // 9
console.log(square instanceof Square); // true