如何“扩展”现有类的现有方法?

时间:2014-02-10 14:34:09

标签: javascript jquery class ember.js

我有一个这样的课程

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");   

输出为Hello Thing is said above!

我试图重新打开该类并再次定义方法,如

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

但是我只留下了Thing is said above!。有没有办法“扩展”一个方法? 或执行类似的任何事情来实现这一目标?

还解释了如何实现同样的扩展jquery方法? ,就像我有一个绑定到DOM元素的jquery方法,我想扩展它以添加更多的代码

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:1)

您可以在扩展版本中调用this._super();,让它调用原始方法。您可以看到here

的示例
相关问题