gpt4 book ai didi

javascript - 如何在 javascript 中扩充父类(super class)中的方法

转载 作者:行者123 更新时间:2023-11-29 16:13:59 24 4
gpt4 key购买 nike

我在基类中有一个方法,我想将其保留在子类中,但只需将其添加即可。我发现了很多关于使用属性和方法扩充类和对象的东西,但我找不到,或者不明白,如何扩充方法。最坏的情况是我必须将父类的整个方法粘贴到子类中,但这似乎是重复代码......请帮忙

function someObject (){
this.someProperty = 1;
this.incrementProperty = function incrementProperty(){
this.propertyOfSomeObject += 1;
}
}

function newObject (){
someObject.call(this);
this.incrementProperty = function incrementProperty(){
//do everything the super class has for this property already
return this.someProperty;
}
}

var incrementer = new newObject;
alert (incrementer.incrementProperty()); //I want output to be 2

最佳答案

// parent object
function someObject () {
this.someProperty = 1;
}

// add incrementProperty to the prototype so you're not creating a new function
// every time you instantiate the object
someObject.prototype.incrementProperty = function() {
this.someProperty += 1;
return this.someProperty;
}

// child object
function newObject () {
// we could do useful work here
}

// setup new object as a child class of someObject
newObject.prototype = new someObject();
// this allows us to use "parent" to call someObject's functions
newObject.prototype.parent = someObject.prototype;
// make sure the constructor points to the right place (not someObject)
newObject.constructor = newObject;

newObject.prototype.incrementProperty = function() {
// do everything the super class has for this property already
this.parent.incrementProperty.call(this);
return this.someProperty;
}

var incrementer = new newObject();
alert (incrementer.incrementProperty()); // I want output to be 2

参见:http://jsfiddle.net/J7RhA/

关于javascript - 如何在 javascript 中扩充父类(super class)中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414591/

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