Javascript对象:从方法访问对象变量(Javascript Objects: Accessing object variables from methods)

编程入门 行业动态 更新时间:2024-10-28 17:23:57
Javascript对象:从方法访问对象变量(Javascript Objects: Accessing object variables from methods)

快速的问题,还有一个我还没有自行解决。 我将从一个例子开始。

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.

更多推荐

本文发布于:2023-08-02 14:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1376881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   变量   方法   Javascript   Objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!