2013-05-02 57 views
1
Parent = (function() { 
    var parent = function(name) { 
     this.name = name; 
    }; 

    parent.prototype.dostuff = function() { 
     console.log(this.name); 
    }; 

    parent.prototype.more = function() { 
     console.log("this should be available on both ... " + this.name); 
    }; 

    return parent; 
}()); 

Child = (function() { 
    var child = function(name) { 
     Parent.call(this, name); 
     this.prototype = Object.create(Parent.prototype); 
    }; 

    child.prototype.dostuff = function() { 
     console.log("the child class ... " + this.name); 
    }; 

    child.prototype.special = function() { 
     console.log("only the child has this method"); 
    }; 

    return child; 
}()); 

在上面我的父對象有一個名爲「更多」的方法,但是當我新的孩子像這樣..我不能調用更多的方法,除非我手動原型。我在上面錯過了什麼,使我能夠免費獲得原型方法?爲什麼子對象沒有使用模塊模式的父方法?

var first = new Parent("father"); 
var last = new Child("son"); 

更新與實例工作的jsfiddle

http://jsfiddle.net/kz7Xk/

回答

1

你設置的原型,你應該把它放在函數本身。

this在構造函數中引用對象本身時創建的對象爲new。但是原型是一個用作構造函數的函數的屬性,而不是實例。

所以,你想是這樣的:

Child = (function() { 
    var child = function(name) { 
     Parent.call(this, name); 
    }; 

    child.prototype = Object.create(Parent.prototype); 

    child.prototype.dostuff = function() { 
     console.log("the child class ... " + this.name); 
    }; 

    child.prototype.special = function() { 
     console.log("only the child has this method"); 
    }; 

    return child; 
}()); 

兒童的原型被設置爲一個新的對象與父母的原型在它的原型,允許它繼承一切。

+0

世界紀錄-whoa那是快:) – 2013-05-02 01:56:37

+0

不應該添加'新'?你知道:'Child = new(function(){...}())'。 – 2013-05-02 02:03:42

+0

我認爲新是另一個選項,而不是Object.create(另一個SO問題談到兩者的優點/缺點) – 2013-05-02 02:04:42

相關問題