我正在尝试装饰一些对象,例如:
Object.prototype.someFunc = function(x) {
if (x == 1) {
return x;
}
return super.someFunc() // <-- ?
}
Run Code Online (Sandbox Code Playgroud)
如何在第二个 return 语句上调用我要重写的函数?
您可以利用继承:
function Parent() { }
Parent.prototype.someFunc = function(x) {
var result = 0;
if (x == 1) {
result = 1;
}
return result;
}
function Child() { }
Child.prototype = Object.create(Parent.prototype); //inheritance
Child.prototype.constructor = Child; //enforce the constructor to be Child instead of Parent
Child.prototype.someFunc = function(x) {
return Parent.prototype.someFunc.call(this, x); //call your Parent prototype someFunc passing your current instance
}
var child = new Child();
console.log(child.someFunc(1)); //1
console.log(child.someFunc(2)); //0
Run Code Online (Sandbox Code Playgroud)
避免扩展原生原型。请参阅https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain