打电话给父母的方法?

时间:2012-11-08 20:39:16

标签: javascript

调用父方法。如何实现?

 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 个答案:

答案 0 :(得分:1)

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

alert(pant.__proto__.year(5)) //5

答案 1 :(得分:1)

以下是Google's Closure Library实现继承的方式:

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功能。

答案 2 :(得分:1)

使this answer适应您的代码:

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

答案 3 :(得分:1)

首先,假设Ch用于" child"和Pant用于" parent",您正在向后执行,这非常令人困惑。当你说

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/