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

相關文章
相關標籤/搜索