2014-02-10 40 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方法,我想扩展它来添加更多的代码。 –