2012-08-08 71 views
2

我想用JavaScript做簡單的經典繼承。我只需要子類和方法重寫,而不是prototype.js或某些其他庫提供的詳細語法和鈴聲和哨聲。現在JavaScript子類化和方法覆蓋

,這個小夥子叫謝爾比S.摩爾已經拿出的作品只是我希望它的方式解決: http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html

唯一的問題是,他擴大本地類型對象和功能打破一些我使用的圖書館。另外作爲一般觀察,我不想混淆本地對象的原型。

我做了謝爾比S. Moore的例子住在這裏: http://jsfiddle.net/christian1974/CEKL5/

你可以從它按預期看到的例子。 現在,64.000美元的問題是:你能否推薦一種使其工作而不與Object.prototype和Function.prototype混淆的方法?

我一直在尋找一個非常簡單的語法,如:

Extend(parent, this); 

如果我只是下降的整體思路,並與這是否現有的庫去?我爲自己讓生活變得困難嗎?

+0

我怕,你不」在JS中繼承了子類。這是一種原型語言,不是基於類的語言。另外,最好的解決方案是創建一個自己的命名空間/對象,只是增加了這個,而不是搞亂本地對象,儘管做得對,擴展這些也是可以的。 – Christoph 2012-08-08 07:34:23

回答

1

,反而增強了對象原型,只是創建一個功能inherits

function inherits(parent) 
{ 
    //just make sure this doesn't get called on the global object (like a regular function) 
    //and the parent is an actual constructor reference 
    if (this === window || typeof parent !== 'function') 
    { 
     throw new Error('inherit not possible on window/without constructor'); 
    } 
    //to set the constructor dynamically and secure the constructor of child object 
    //I'd say this should do the trick (be weary though, not tested) 
    var constr, Proto; 
    constr = this.constructor; 
    Proto = typeof parent === 'function' ? new parent : parent;//get instance 
    this.prototype = Proto.prototype; 
    this.constructor = constr;//restore constructor when needed 
    if(arguments.length > 1) 
    { 
     return parent.apply(this, Array.prototype.slice.call(arguments, 1)); 
    } 
    return parent.call(this); 
} 

function Foo(someArg) 
{ 
    inherits.apply(this,[Bar,someArg]); 
} 

話雖這麼說,我真的沒有看到這種方法的好處了,說,Object.create和 - 由於你使用libs- jQuery的.extend方法

+0

這幾乎完美!唯一的事情。父類的原型不會傳遞給子類。 – ChrisRich 2012-08-08 08:02:37

+0

我更新了代碼來解決這個問題。沒有測試,但在理論_這應該工作 – 2012-08-08 08:11:18

+0

看看我發現!正是我期待的:http://ejohn.org/blog/simple-javascript-inheritance/ – ChrisRich 2012-08-09 00:45:50

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

用法:爲什麼不是

function Parent() {} 

Parent.prototype.hello = function(name) { 
    alert('hello ' + name); 
} 

function Child() { 
    Child.superclass.hello.call(this, 'world'); 
} 

extend(Child, Parent); 
+0

感謝韋德。你會如何將參數傳遞給超級? – ChrisRich 2012-08-08 07:27:16

+0

我已附加到答案。 – darthwade 2012-08-08 07:58:25