访问对象属性内的变量 [英] Accessing variable inside object property

查看:80
本文介绍了访问对象属性内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了一个问题。我有这个名为 myTree 的对象。而且该对象具有属性。其中一个属性包含如下方法:

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:

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

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

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

我在jsFiddle上做了一个演示,在JavaScript窗口的末尾你可以看到我正在警告对象 prep 其中包含 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 prep in which myarray is contained.

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

推荐答案

JavaScript变量是函数作用域。无法从外部范围访问属于内部范围的变量(即function)。

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

如果你想要那种对于访问,您必须使外部范围的相应变量部分。

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 this keyword.

通过 object literal 语法定义对象时( obj = {prop:value} )而不是通过构造函数(函数Obj(value){this.prop = value;}; obj = new Obj(value) ; ),然后默认情况下所有已定义的属性都将是公共。

When you define an object via the object literal syntax (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.

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

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

仍然无法从外部访问内部范围变量。没有办法解决这个问题。

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).

这篇关于访问对象属性内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆