Javascript嵌套原型方法作用域
Javascript nested prototype method scope
下面是我要执行的示例代码。
var Game = function(){
this.state = 'yeah';
}
Game.prototype.call = function(){
document.writeln(this.state);
Game.prototype.say();
}
Game.prototype.say = function(){
document.writeln(this.state);
}
game = new Game();
game.call();
结果是yeah undefined
,这意味着call()
工作正常,而say()
不是。我怎么做才能得到say()
函数。状态从游戏对象?
Game.prototype.call = function(){
document.writeln(this.state);
this.say();
}
prototype用于定义函数而不是调用它
千万不要重写本地方法(比如本例中的call
).
也可以这样
Game.prototype.call = function(){
document.writeln(this.state);
Game.prototype.say.apply(this);
}
看起来你想要的是:
Game.prototype.call = function(){
document.writeln(this.state);
this.say();
}
但是这个版本将调用在this.say
设置的任何函数,如果对象被继承,该函数可能被覆盖:
var MyGame = function () {};
MyGame.prototype = new Game();
MyGame.prototype.say = function () {
document.writeln('something else');
};
var m = new MyGame();
m.call(); //'something else'
如果您想使用对Game.prototype.say
的原始引用(没有继承),那么您需要在对象的上下文中调用该函数:
Game.prototype.call = function(){
document.writeln(this.state);
Game.prototype.say.call(this);
}
var m = new MyGame();
m.call(); //'yeah'
TGH给了你一个解决方案,但没有解释。你的问题在这里:
> Game.prototype.say();
您正在调用say
作为Game.prototype
的方法,因此在函数中:
> Game.prototype.say = function(){
> document.writeln(this.state);
> }
this
是对原型对象的引用,而不是实例。您希望以如下方式调用该函数:
this.say();
使其作为实例的方法调用,从而将say
中的this
设置为实例
相关文章:
- 在put方法之前从作用域获取数据
- Visual Studio展开方法和所有子作用域或仅折叠方法
- 为什么't我的角度控制器'在其某个方法内的作用域中的依赖项
- 直接在DOM事件处理程序中调用作用域函数的最短方法是什么
- 尝试将变量传递到对象中时的作用域问题'的方法构造函数
- 在对象类上实现 jquery 作用域的最佳方法
- 从多个控制器上的指令访问作用域的正确方法
- 有没有办法迭代函数作用域内的公共方法
- 使用类/构造函数与变量方法时的作用域不同
- JavaScript 中的范围(为什么在 $.post() 方法数组的作用域是本地的?)
- 描述从回调方法获取正确的作用域
- 作用域问题反应父子方法ES6
- JavaScript——如何将作用域传递给reader.onload方法
- 数组排序方法内部的作用域
- 作用域或控制器上的Angular js difference方法
- 在全局作用域上调用Object.prototype方法
- 使用 JSON 对 js 对象进行分级/解析时,返回的方法中的函数作用域会丢失
- 用JavaScript编写块作用域的最短方法是什么
- 全局作用域映射的Javascript方法
- 将作用域变量传递给作用域方法