5)Javascript設計模式:extends模式

簡單的方式

function Person() {
    this.name = 'person';
}
Person.prototype.say = function() {};

function Child() {
    this.name = 'child';
}
Child.prototype = new Person();
 
var child = new Child();

缺點:其實child並不須要person裏面的name屬性

借用構造函數

function Person() {
    this.name = 'person';
}
Person.prototype.say = function() {};

function Child() {
     Person.call(this, arguments)
}

var child = new Child();

缺點:僅會複製父類對象的屬性做爲子類自身的屬性, 僅僅是複製**

優勢:能夠得到父對象自身的真實副本,子類和父類沒有關係,不會影響到父類**

借用構造函數是實現多繼承

function CatWings() {
     Cat.call(this, arguments)
     Brid.call(this, arguments)
}

借用構造函數和實現原型

function Person() {
    this.name = 'person';
}
Person.prototype.say = function() {};

function Child() {
     Person.call(this, arguments)
    // this.name = 'child'
}

Child.prototype = new Person()

var child = new Child();
delete child.name;
// 能夠看到訪問:child.name的是prototype的

name屬性被繼承了2次

缺點:全部從Person繼承的類,都是能夠更改到Person的原型方法

臨時構造函數

function inherit(Child, Parent) {
    var F = function(){}
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    // Child.prototype.constructor = Child
    // Child.superclass = Parent.prototype;
}

// 每次都要建立一個空的F
var inherit = (function(){
    var F = Function(){};
    return function() {
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        // Child.prototype.constructor = Child
        // Child.superclass = Parent.prototype;
    }
})();

Klass

var Klass = function (Parent, props) {

    if(props == undefined && typeof Parent == 'object') {
        props = Parent;
        Parent = null;
    }

    Parent = Parent || {};
    props = props || {};

    var Child = function() {
        if(Child.superclass.hasOwnProperty('__construct')) {
            Child.superclass['__construct'].apply(this, arguments);
        }

        if(Child.prototype.hasOwnProperty('__construct')) {
            Child.prototype['__construct'].apply(this, arguments);
        }
    };


    var F = function() {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.superclass = Parent.prototype;

    for(var i in props) {
        if(props.hasOwnProperty(i)) {
            Child.prototype[i] = props[i];
        }
    }
    return Child;
}

function Animal() {}

Animal.prototype.__construct = function(name) {
    this.name = name
};

Animal.prototype.getName = function() {
    return this.name;
};

var Dog = Klass(Animal, {
    __construct: function(name, age) {
        this.age = age;
    },
    run: function() {
        console.log('My name is %s, I\'m %s years old ,  I\'m Running', this.getName(), this.age);
    }
});

var dog = new Dog('xixi', 26)
相關文章
相關標籤/搜索