How is 'this' working in this context?
This question already has an answer here:
The mainState is an object literal. 'prototype' is a property of function object in javascript used for prototype inheritance. Javascript Prototype
有一件事总是帮助我记住this
将是什么,以查找谁在调用函数,请检查此代码段
var sayHi = function() { console.log(this.name) }
var yoda = { name: "Yoda", sayHi: sayHi }
var darthVader = { name: "Anakin Skywalker", sayHi: sayHi }
// the `this` here will be the yoda object
yoda.sayHi()
// the `this` here will be the darthVader object
darthVader.sayHi()
window.name = "Global name"
// here, since nothing was specified, the object is the global object, or the window on browsers, this the same as "window.sayHi()"
sayHi()
如果你想在原型上使用你的方法,你可以创建一个MainState
构造函数,并附上你的原型方法:
function MainState(game) {
this.game = game;
}
MainState.prototype.create = function() {
this.bird = this.game.add.sprite(100, 245, 'bird');
};
MainState.prototype.myFunction = function() { };
// etc.
var mainState = new MainState(game);
mainState.myFunction();
链接地址: http://www.djcxy.com/p/94904.html
上一篇: 为什么我的变量undefined在Underscore.js中的每个函数中?
下一篇: 'this'在这种情况下如何工作?