2014-02-10 41 views
2

我有這樣如何「擴展」現有類的現有方法?

App.Person = Ember.Object.extend({ 
    say: function(thing) { 
    alert(thing); 
    } 
}); 

我想添加一些方法say,因此該方法變得

App.Person = Ember.Object.extend({ 
    say: function(thing) { 
    alert(thing); 
    alert("Thing is said above! "); 
    } 
}); 

一類,以便

var person = App.Person.create(); 
person.say("Hello"); 

輸出是HelloThing is said above!

我試圖重新打開類,並再次定義方法類似

App.Person.reopen({ 
    say: function(thing) { 
    alert("Thing is said above! "); 
    } 
}); 

但後來我只剩下Thing is said above!我。有沒有辦法「擴展」一種方法? 或執行任何類似的操作來實現此目的?

也解釋瞭如何實現同樣的擴展jquery方法? ,就像我有綁定到一個DOM元素的jquery方法,我想擴展它以添加更多的代碼

回答

2

我想是的。要麼你調用父類的功能分爲繼承功能:

// Super class 
function Person() { 
    this.text = "Hello"; 
} 
Person.prototype.say = function() { 
    alert(this.text); 
} 

// Inherited class 
function TalkativePerson() { 
    Person.apply(this); // Call to the super constructor 
    this.extendedText = "How are you ?"; 
} 
TalkativePerson.prototype = Object.create(Person.prototype); // Inheritance 
TalkativePerson.prototype.constructor = TalkativePerson; 
TalkativePerson.prototype.say = function() { // Here you redefine your method 
    Person.prototype.say.call(this);//And then you call the super method 
    // Add some stuff here like this : 
    alert(this.extendedText); 
} 

var person = new TalkativePerson(); 
person.say(); 

或者你可以(在你的例子)直接更改文本的像這樣的值:

function TalkativePerson2() { 
    this.text += ". How are you ?"; 
} 
TalkativePerson2.prototype = new Person(); 

Here是的jsfiddle在那裏你可以測試它。

+0

用Object.create(shim for old browsers)設置繼承的原型部分會更好,並通過在Child或Person.call中調用'Parent.call(this,args);'來使用Parent構造函數(this,args );'在TalkativePerson中,即使沒有參數用於初始化實例成員,您可能希望將來再使用Person構造函數,並且值得一提的是如何。更多的信息在這裏:http://stackoverflow.com/a/16063711/1641941雖然OP使用Ember.js(我認爲)與對象定義「幫助」,所以沒有閱讀文檔時不知道發生了什麼的方式。 – HMR

+0

@HMR我更新了我的答案 –

1

您可以在擴展版本中調用this._super();讓它調用原始方法。你可以看到一個例子here

+0

感謝幫助,但你也可以解釋如何實現相同的擴展jQuery方法嗎? ,就像我有綁定到DOM元素的jquery方法,我想擴展它來添加更多的代碼。 –