Javascript 重写继承对象的方法
我有以下代码:Javascript 重写继承对象的方法,javascript,prototype-chain,Javascript,Prototype Chain,我有以下代码: var Base = function () { // do stuff } Base.prototype.foo = function () { console.log("foo"); } Base.prototype.someMethods = { methodOne: function () { console.log("methodOne"); }, methodTwo: function () { console
var Base = function () {
// do stuff
}
Base.prototype.foo = function () {
console.log("foo");
}
Base.prototype.someMethods = {
methodOne: function () {
console.log("methodOne");
},
methodTwo: function () {
console.log("methodTwo");
}
};
var myClass = function () {
Base.call(this);
}
myClass.prototype = Object.create(Base.prototype);
myClass.constructor = myClass;
myClass.prototype.foo = function () {
console.log("myClass")
Base.prototype.foo.call(this);
};
myClass.prototype.someMethods.methodOne = function () {
console.log("myClass");
Base.prototype.someMethods.call(this);
};
当创建myClass
的实例时,对myClass.foo()
的调用将按预期工作。它将调用myClass
方法,然后作为该逻辑的一部分调用基本构造函数方法
但是,myClass.prototype.someMethods.methodOne
实际上将覆盖Base.prototype.someMethods.methodOne
(console.log(Base.prototype.someMethods.methodOne)
显示myClass函数)
因此,调用
Base.prototype.somemethods.call(this)
会创建无限递归
你能解释一下为什么会这样吗?对于someMethods
对象的方法,如何以不同的方式创建原型链
要使此代码正常工作,我需要知道什么?
Base.prototype。某些方法
没有调用方法。你是说Base.prototype.somemethods.methodOne
?如果您绝对想要嵌套,请使用适当的继承链将somemethods
作为其自身适当类的实例