1

调用父方法。如何实现?

 function Ch() {
        this.year = function (n) {
            return n
        }
    }

    function Pant() {
        this.name = 'Kelli';
        this.year = function (n) {
            return 5 + n
        }
    }

//扩展

 Pant.prototype = new Ch();
    Pant.prototype.constructor = Pant;
    pant = new Pant();
    alert(pant.name); //Kelli
    alert(pant.year(5)) //10

如何调用所有父方法

this.year = function (n) {
            return 5 + n
        } 

在对象?谢谢大家的帮助

4

4 回答 4

1

您可以调用重写的超类(父)方法,__proto__但 IE 不支持

alert(pant.__proto__.year(5)) //5
于 2012-11-08T20:50:30.970 回答
1

下面是Google 的 Closure 库是如何实现继承的:

goog.inherits = function(childCtor, parentCtor) {
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  childCtor.prototype.constructor = childCtor;
};

然后您的代码将变为:

function Ch() {}
Ch.prototype.year = 
function (n) {
   return n
}

function Pant() {}
goog.inherits(Pant,Ch);
Pant.prototype.name = 'Kelli';
Pant.prototype.year = function (n) {
   return 5 + Pant.superClass_.year.call(this, n);//Call the parent class
}

pant = new Pant();
alert(pant.name); //Kelli
alert(pant.year(5)) //10

如果您愿意,您当然可以重命名该goog.inherits函数。

于 2012-11-08T20:53:36.730 回答
1

将此答案改编为您的代码:

function Ch() {
    this.year = function(n) {
        return n;
    }
}

function Pant() {
    Ch.call(this); // make this Pant also a Ch instance
    this.name = 'Kelli';
    var oldyear = this.year;
    this.year = function (n) {
        return 5 + oldyear(n);
    };
}
// Let Pant inherit from Ch
Pant.prototype = Object.create(Ch.prototype, {constructor:{value:Pant}});

var pant = new Pant();
alert(pant.name); // Kelli
alert(pant.year(5)) // 10
于 2012-11-08T20:58:34.830 回答
1

首先,假设Ch是“孩子”,而Pant“父母”是倒着做的,这非常令人困惑。当你说

Pant.prototype = new Ch();

您正在Pant继承自Ch. 我假设这就是您的意思,并且您想调用返回的方法n,而不是返回的方法n + 5。所以你可以这样做:

function Ch() {
    this.year = function (n) {
        return n;
    }
}

function Pant() {
    this.name = 'Kelli';
    this.year = function (n) {
        return 5 + n;
    }
}

Pant.prototype = new Ch();
Pant.prototype.constructor = Pant;
pant = new Pant();
alert(pant.name); //Kelli
alert(pant.year(5)) //10

// Is the below what you need?
alert(Pant.prototype.year(5)); // 5

http://jsfiddle.net/JNn5K/

于 2012-11-08T21:12:16.723 回答