Javascript 在javascript中调用另一个原型方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8778874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:29:04  来源:igfitidea点击:

Calling one prototype method inside another in javascript

javascriptoopprototype

提问by indianwebdevil

var Ob = function(){


}

Ob.prototype.add = function(){
    inc()

}

Ob.prototype.inc = function(){
    alert(' Inc called ');

}

window.onload = function(){
var o = new Ob();
o.add();
}

I would like to call something like this,how can i call, ofcourse i put incas inner function to addI can do that but without having the inner function. how do i do that ?

我想调用这样的东西,我怎么能调用,当然我把inc作为内部函数来添加我可以做到这一点,但没有内部函数。我怎么做 ?

回答by bjornd

It's easy:

这很简单:

Ob.prototype.add = function(){
    this.inc()
}

Ob.prototype.inc = function(){
    alert(' Inc called ');
}

When you create the instance of Obproperties from prototype are copied to the object. If you want to access the methods of instance from within its another method you could use this.

当您Ob从原型创建属性实例时,将复制到对象中。如果您想从另一个方法中访问实例的方法,您可以使用this.