装饰原型并调用父函数

时间:2015-12-27 16:21:43

标签: javascript

我试图装饰一些对象,例如:

Object.prototype.someFunc = function(x) {
  if (x == 1) {
      return x;
  } 

  return super.someFunc() // <-- ? 
}

如何在第二个返回语句中调用我覆盖的函数?

4 个答案:

答案 0 :(得分:2)

你可以利用继承:

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

避免扩展原生原型。见https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

答案 1 :(得分:0)

var _someFunc = Object.prototype.someFunc;
Object.prototype.someFunc = function(x) {
  // ...
  return _someFunc.call(this, x/*, other args*/);
}

答案 2 :(得分:0)

您需要备份。说:

var __superFunc = Object.prototype.someFunc;
Object.prototype.someFunc = function(x) {
  if (x == 1) {
      return x;
  }

  return __superFunc.call(this, x);
}

答案 3 :(得分:-1)

整个代码必须重写;你还需要为父项指定函数的行为(以防止递归调用)...这是一个提示,使用调用方法:

Object.prototype.someFunc.call(this, x);

在javascript中,没有真正的继承本机实现