「这个」没有 hack 就无法在私有 JavaScript 函数中访问对象吗?

发布于 2024-09-10 11:48:51 字数 572 浏览 5 评论 0原文

我在一个项目上工作了一段时间,试图找出我做错了什么,当我最终将“错误”范围缩小到以下代码无法按我预期工作的事实时:

function Alpha()
    {
    this.onion = 'onion';

    function Beta()
        {
        alert(this.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'undefined'

但是,如果我更改代码如下:

function Alpha()
    {
    var self = this;
    this.onion = 'onion';

    function Beta()
        {
        alert(self.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'onion'

它的工作原理就像我所期望的那样。在浪费了我生命的很大一部分之后,有人能解释为什么它会这样吗?

I was working on a project for a while, trying to figure out what I was doing wrong, when I finally narrowed "the bug" down to the fact that the below code doesn't work as I expected:

function Alpha()
    {
    this.onion = 'onion';

    function Beta()
        {
        alert(this.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'undefined'

However, if I change the code to this:

function Alpha()
    {
    var self = this;
    this.onion = 'onion';

    function Beta()
        {
        alert(self.onion);
        }

    Beta();
    }

alpha1 = new Alpha();
// Alerts 'onion'

it works like I would expect. After wasting a large portion of my life, can anyone explain why it works like this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我纯我任性 2024-09-17 11:48:51

之所以如此工作,是因为每个函数都关联了自己的执行上下文。

但是还有其他方法可以做到这一点,例如:

使用 调用申请来调用函数:

function Alpha() {
  this.onion = 'onion';

  function Beta() {
    alert(this.onion);
  }

  Beta.call(this);
}

var alpha1 = new Alpha();
// Alerts 'onion'

新的 ECMAScript 第 5 版标准引入了一种保存函数上下文的方法,即 Function.prototype.bind 方法:

function Alpha() {
  this.onion = 'onion';

  var Beta = function () {
    alert(this.onion);
  }.bind(this);

  Beta();
}

var alpha1 = new Alpha();
// Alerts 'onion'

我们可以说 Beta 函数是绑定,无论你如何调用它,它的this值都将是完整的。

此方法尚未得到广泛支持,目前仅 IE9pre3 包含它,但您可以包含 一个实现使其现在可以工作。

现在让我详细说明 this 的工作原理:

this 值存在于每个 执行上下文,并且对于在进行函数调用时隐式设置的函数代码,该值取决于引用的形成方式。

在您的示例中,当您调用 Beta(); 时,由于它未绑定到任何对象,因此我们可以说该引用没有基对象,然后, < code>this 值将引用全局对象。

当您调用绑定为对象属性的函数时,会发生其他情况,例如:

var obj = {
  foo: function () { return this === obj;}
};
obj.foo(); // true

如您所见,被调用的引用 obj.bar(); 包含一个基对象,该基对象是obj,并且被调用函数内的this值将引用它。

注意引用类型是一个抽象概念,为语言实现目的而定义,您可以在规范中查看详细信息。

隐式设置 this 值的第三种情况是当您使用 new 运算符,它将引用一个新创建的对象,该对象继承自其构造函数的原型:

function Foo () {
  return this; // `this` is implicitly returned when a function is called 
}              // with `new`, this line is included only to make it obvious

var foo = new Foo();
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true

Works like this because each function has associated its own execution context.

However there are other ways to do it, for example:

Using call or apply to invoke the function:

function Alpha() {
  this.onion = 'onion';

  function Beta() {
    alert(this.onion);
  }

  Beta.call(this);
}

var alpha1 = new Alpha();
// Alerts 'onion'

The new ECMAScript 5th Edition Standard, introduces a way to persist the function context, the Function.prototype.bind method:

function Alpha() {
  this.onion = 'onion';

  var Beta = function () {
    alert(this.onion);
  }.bind(this);

  Beta();
}

var alpha1 = new Alpha();
// Alerts 'onion'

We can say that the Beta function is bound, and no matter how you invoke it, its this value will be the intact.

This method is not widely supported yet, currently only IE9pre3 includes it, but you can include an implementation to make it work now.

Now let me elaborate about how this works:

The this value exist on each execution context, and for Function Code is set implicitly when a function call is made, the value is determined depending how the reference if formed.

In your example, when you invoke Beta();, since it is not bound to any object, we can say that the reference has no base object, then, the this value will refer to the global object.

Other case happens when you invoke a function that is bound as a property of an object, for example:

var obj = {
  foo: function () { return this === obj;}
};
obj.foo(); // true

As you can see, the reference being invoked obj.bar(); contains a base object, which is obj, and the this value inside the invoked function will refer to it.

Note: The reference type is an abstract concept, defined for language implementation purposes you can see the details in the spec.

A third case where the this value is set implicitly is when you use the new operator, it will refer to a newly created object that inherits from its constructor's prototype:

function Foo () {
  return this; // `this` is implicitly returned when a function is called 
}              // with `new`, this line is included only to make it obvious

var foo = new Foo();
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
素染倾城色 2024-09-17 11:48:51

来自JavaScript:权威指南,第五版(犀牛书):

当一个函数被调用时
函数而不是方法,
this 关键字指的是全局
目的。令人困惑的是,这甚至是真的
当调用嵌套函数时(如
包含方法内的函数)
作为方法调用:this
关键字有一个值
包含函数但是
(违反直觉)指的是
体内的全局对象
嵌套函数。

请注意,this 是关键字,而不是
变量或属性名称。 JavaScript
语法不允许您分配
this

这里需要注意两件事:

  1. this 不是变量,因此正常的闭包捕获规则不适用。
  2. this 在每次函数调用时都会“反弹”,无论是作为方法、普通函数调用还是通过 new 调用。由于您正在进行正常的函数调用(调用 Beta 时),因此 this 会绑定到“全局对象”。

From JavaScript: The Definitive Guide, 5th Edition (the rhino book):

When a function is invoked as a
function rather than as a method, the
this keyword refers to the global
object. Confusingly, this is true even
when a nested function is invoked (as
a function) within a containing method
that was invoked as a method: the this
keyword has one value in the
containing function but
(counterintuitively) refers to the
global object within the body of the
nested function.

Note that this is a keyword, not a
variable or property name. JavaScript
syntax does not allow you to assign a
value to this.

Two things to pay attention to here:

  1. this isn't a variable, so the normal closure capture rules don't apply.
  2. this is "rebound" on every functiion calls, whether as a method, a normal function call, or via new. Since you're doing a normal function call (when calling Beta), this is getting bound to the "global object".
花开浅夏 2024-09-17 11:48:51

当您调用非成员函数(不称为 someObject.method())时,它在窗口的上下文中运行。它是私有函数还是全局函数并不重要。

您可以这样做:

Beta.call(this);

call 允许您在调用函数时传递上下文作为第一个参数(apply 类似,但参数列表是一个数组)。

但是,我不清楚(即使对于这个微不足道的例子)为什么洋葱是公开的而 Beta 是私有的。

When you call a non-member function (not called as someObject.method()), it runs in the context of the window. It doesn't matter whether it's a private function or a global one.

You could do:

Beta.call(this);

call allows you to call a function while passing a context as the first argument (apply is similar, but the argument list is an array).

However, I'm not clear (even for the trivial example) why onion is public but Beta is private.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文