2014-06-05 45 views
0

JavaScript中有繼承的標準方式嗎? 任何標準函數,我可以用於繼承,我只是傳遞兩個對象(或構造函數),它做需要。JavaScript中的繼承標準功能

+0

我還沒有看到任何「helper」函數完全處理JavaScript中的繼承,因爲編寫這樣的函數太複雜了,而且您仍然需要自己做很多事情。要在JavaScript中繼承,您需要設置child.prototype並在子構造函數'Parent.apply(this,arguments)中調用父構造函數'當想要擴展Parent函數時,可以像調用Parent.prototype .someExtendedMethod.call(this,args);'更多信息可以在這裏找到:http://stackoverflow.com/a/16063711/1641941 – HMR

+0

我不確定,但大多數JavaScript庫使用修復輔助函數進行繼承,他們通過父母和孩子作爲參數。 –

回答

2

如果使用Node.js的,那麼你可以使用util.inherits功能可按,這樣

util.inherits(MyStream, events.EventEmitter); 

這裏,MyStream是孩子和events.EventEmitter是父。

否則,你可以簡單地使用下面的代碼

Child.prototype = Object.create(Parent.prototype); 
Child.prototype.constructor = Child; 
+0

我正在使用JavaScript主要用於UI中的DOM操作。 我認爲第二個不適用於對象。 –

+0

@SushilKumar你能舉個例子嗎?我列出的方法是繼承的常用方法。 – thefourtheye

+1

在開始嘗試使用DOM對象繼承之前,請閱讀[*擴展DOM *有什麼問題](http://perfectionkills.com/whats-wrong-with-extending-the-dom/)「...的缺點這看似有用的做法「。使用[* native objects *](http://ecma-international.org/ecma-262/5.1/#sec-4.3.6)是很好的,但[* host objects *](http:// ecma-international .org/ecma-262/5.1 /#sec-4.3.8)對他們自己來說是一種法律。 – RobG

0

這是Sharpkit compiler爲繼承產生的示例代碼,希望它能幫助:)

if (typeof($Inherit) == 'undefined') { 
    var $Inherit = function(ce, ce2) { 
     if (typeof(Object.getOwnPropertyNames) == 'undefined') { 
      for (var p in ce2.prototype) 
       if (typeof(ce.prototype[p]) == 'undefined' || ce.prototype[p] == Object.prototype[p]) 
        ce.prototype[p] = ce2.prototype[p]; 
      for (var p in ce2) 
       if (typeof(ce[p]) == 'undefined') 
        ce[p] = ce2[p]; 
      ce.$baseCtor = ce2; 
     } else { 
      var props = Object.getOwnPropertyNames(ce2.prototype); 
      for (var i = 0; i < props.length; i++) 
       if (typeof(Object.getOwnPropertyDescriptor(ce.prototype, props[i])) == 'undefined') 
        Object.defineProperty(ce.prototype, props[i], Object.getOwnPropertyDescriptor(ce2.prototype, props[i])); 

      for (var p in ce2) 
       if (typeof(ce[p]) == 'undefined') 
        ce[p] = ce2[p]; 
      ce.$baseCtor = ce2; 
     } 
    } 
}; 
+0

你能解釋一下嗎?哪一個是孩子,哪一個是父母對象? –

+0

這不會繼承,它結合了2個對象。 – HMR

0

有沒有什麼標準的方法在JavaScript中繼承?

是的,原型繼承。這是in the spec。基本模式:

// Constructor 
function Foo(name) { 
    this.name = name; 
} 

// Constructor's prototype holds properties inherited by instances 
Foo.prototype.sayName = function() { return this.name } 

// Use new to create an instance 
var foo = new Foo('foo'); 

alert(foo.sayName()); // foo 

您還可以模擬各種其他類型的繼承,但通常這不是一個好主意(或去幻想與任何一種在JavaScript中繼承的,它只是並不需要它) 。有時候它有幫助。

Search the interwebshere on SO,有數以千計的文章,博客和答案。

任何標準的功能,我可以使用繼承

thefourtheye的回答和Object.create