javascript 访问对象属性内的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11291323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:39:33  来源:igfitidea点击:

Accessing variable inside object property

javascriptobjectscope

提问by madeye

So I encountered a problem. I have this object called myTree. And that object has properties. One of the properties contains a method like this:

所以我遇到了一个问题。我有这个对象叫做myTree. 该对象具有属性。其中一个属性包含这样的方法:

prep: function (variable) {
    /* some code */
}

In that method there is an array myarrayand I want to know, whether it is possible to access the content of that array, and if it is, how I would do that.

在那个方法中有一个数组myarray,我想知道,是否可以访问该数组的内容,如果可以,我将如何做到这一点。

I've made a demo on jsFiddle, and in the end of the JavaScript window you can see that I'm alerting the object prepin which myarrayis contained.

我做了对的jsfiddle演示,并在JavaScript窗口结束时,你可以看到,我提醒对象prepmyarray包含。

http://jsfiddle.net/Wp7Xh/1/

http://jsfiddle.net/Wp7Xh/1/

回答by Tomalak

JavaScript variables are function-scoped. It is not possible to access variables belonging to an inner scope (i.e. "function") from an outer scope.

JavaScript 变量是函数作用域的。不可能从外部作用域访问属于内部作用域(即“函数”)的变量。

If you want that kind of access, you must make the respective variable part of the outer scope.

如果您想要这种访问,您必须使外部作用域的相应变量部分。

var myTree = function() {
  var myarray = [];

  this.prep = function (variable) {
    myarray.push(variable);
  };
}

In your scenario, where you have nested objects, it's quite similar:

在您有嵌套对象的场景中,它非常相似:

var myTree = {
  myarray: [],
  prep: function (variable) {
    this.myarray.push(variable);
  }
}

The only difference is the use of the thiskeyword.

唯一的区别是this关键字的使用。

When you define an object via the object literalsyntax (obj = {prop: value}) instead of via a constructor (function Obj(value) { this.prop = value; }; obj = new Obj(value);), then all defined properties will be "public" by default.

当您通过对象字面量语法 ( obj = {prop: value}) 而不是构造函数 ( function Obj(value) { this.prop = value; }; obj = new Obj(value);) 定义对象时,默认情况下所有定义的属性都将是“公共的”。

When you call a function on that object, thiswill point to the respective object instance.

当您对该对象调用函数时,this将指向相应的对象实例。

Accessing an "inner scope" variable from outside is still impossible. There's no way around that.

从外部访问“内部范围”变量仍然是不可能的。没有办法解决这个问题。

Generally speaking: You can access properties of the objects you construct. You can never access function local variables (except from the inside of nested functions).

一般而言:您可以访问您构造的对象的属性。你永远不能访问函数局部变量(除了从嵌套函数内部)。