JavaScript继承模式

call、apply方法

做用:改变this指向javascript

区别:传参列表不一样java

咱们经过一个实际案例来看app

function Father(name, age, hobby) {
    this.name = name;
    this.age = age;
    this.hobby = hobby;
}
function Son(name, age, hobby, grade) {
    Father.call(this, name, age, hobby);
    this.grade = grade;
}
var son = new Son("xiaozhuan", 13, "football", "2000");
复制代码

call和apply还有一种引用:假设一个对象a中有一个方法b,还有一个c对象a.b.call(c); 意思是使c对象调用a中的b方法。apply类推同样的,当咱们改变改变this指向时放入call括号内还能够放入调用方法的参数,看下面例子:ui

var arr = [1,2,3,4,5,6,7]
var arr1 = Array.prototype.slice.call(arr, 0, 3);
console.log(arr1);
复制代码

圣杯模式继承

Father.prototype.hobby="football";
function Father(age) {
    this.age = age; 
}
function Son(name){
    this.name = name;
}
function inherit (a,b) {
    function F(){};
    F.prototype = a.prototype;
    b.prototype = new F();
    b.prototype.constuctor=b;
}
inherit(Father, Son);
var father =new Father(31);
var son=new Son("xiaoli");
复制代码

这样咱们能够作到使对象通用一个原型来继承属性。this

相关文章
相关标签/搜索