[英]unable to access public method from private method
我知道有很多关于JS中的私有/公共方法如何工作的话题,但是没有一个能解决我当前遇到的问题。
如您在下面看到的,我只是尝试从私有方法访问公共方法。
function Animal(name) {
this.name = name
}
Animal.prototype = (function()
{
var sitdown = function() {
console.log(this.name + ' sits down.');
standup();
};
return {
standup: function()
{
console.log(this.name+' stands up');
sitdown();
}
}
})();
var Tiger = new Animal("Tiger");
Tiger.standup();
一切正常,直到进入standup()方法为止。
我能解决这个问题吗?
谢谢,亚历克斯
您没有使用var sit
在作用域中定义函数standup
,您需要更改代码,例如
Animal.prototype = (function()
{
var sit = function() {
console.log(this.name + ' sits down.');
standup();
};
function standup()
{
console.log(this.name+' stands up'); //`this` here is global object, not your created
}
return {
standup: standup
}
})();
更新:更新OP方法后,您需要这样的东西
Animal.prototype = (function()
{
var sitdown = function() {
console.log(this.name + ' sits down.');
standup.call(this);
},
standup = function (){
console.log(this.name+' stands up');
}
return {
standup: function()
{
sitdown.call(this);
}
}
})();
也更多关于this
关键词
删除退货,一切应该正常。
function Animal(name) {
this.name = name
}
Animal.prototype = (function()
{
var sit = function() {
console.log(this.name + ' sits down.');
standup();
};
var standup = function()
{
console.log(this.name+' stands up');
};
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.