快速的问题,还有一个我还没有自行解决。 我将从一个例子开始。
object = { somevariable: true, someothervariable:31, somefunction: function(input){ if (somevariable === true){ return someothervariable+input; } } } object.somefunction(3);显然这是行不通的。 我是否必须说object.somevariable和object.someothervariable或者是否有引用属于本地对象的变量的方法,而不必明确地引用对象?
谢谢
Gausie
Quick question, and one I am yet to work out on my own. I'll start with an example.
object = { somevariable: true, someothervariable:31, somefunction: function(input){ if (somevariable === true){ return someothervariable+input; } } } object.somefunction(3);Obviously this won't work. Do I have to say object.somevariable and object.someothervariable or is there a means of referring to variables that are part of the local object, without referring to the object explicitly?
Thanks
Gausie
最满意答案
使用特殊关键字this ,它引用一个函数被调用的对象:
var thing = { somevariable: true, someothervariable:31, somefunction: function(input){ if (this.somevariable === true){ return this.someothervariable+input; } } } thing.somefunction(3); var otherThing = { somevariable: true, someothervariable:'foo', amethod: thing.somefunction }; otherThing.amethod('bar');小心使用变量名称,如“对象”。 JS区分大小写,所以它不会与内部Object发生冲突,但是您可能会在其他语言中遇到麻烦。
Use the special keyword this, which refers to the object a function was invoked on:
var thing = { somevariable: true, someothervariable:31, somefunction: function(input){ if (this.somevariable === true){ return this.someothervariable+input; } } } thing.somefunction(3); var otherThing = { somevariable: true, someothervariable:'foo', amethod: thing.somefunction }; otherThing.amethod('bar');Be careful about using variable names like "object". JS is case-sensitive, so it won't collide with the intrinsic Object, but you might get into trouble in other languages.
更多推荐
发布评论