gpt4 book ai didi

javascript - 如何 "extend"现有类的现有方法?

转载 作者:行者123 更新时间:2023-11-29 19:43:14 25 4
gpt4 key购买 nike

我有这样一个类

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 方法? ,就像我有绑定(bind)到 DOM 元素的 jquery 方法,我想扩展它以添加更多代码

最佳答案

我认为是的。要么将 super 函数调用到继承函数中:

// 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,您可以在其中对其进行测试。

关于javascript - 如何 "extend"现有类的现有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21679969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com