gpt4 book ai didi

javascript - 了解 'this' 对象上下文

转载 作者:行者123 更新时间:2023-11-30 10:31:18 25 4
gpt4 key购买 nike

我不明白当不使用 new 关键字时,BigObject 构造函数中的 this 怎么会是 undefined -- 请参阅下面的示例。在 Firebug 中给出以下代码片段:

( function( global ){  
"use strict";
var fromunderbutter = "fun";
global.BigObject = function( options ){
console.log( this );
console.log( this instanceof BigObject );
};
})( this );

下面的代码是有道理的:

>>> var x = new BigObject();
>>> Object { } // new constructor creates blank object context that is assigned to BigObject
>>> true // BigObject was the object context ( this ) that invoked BigObject()

据我了解,this 指的是当前对象上下文。在上面的示例中,由于 new 关键字,this 将引用一个空白对象,该对象将新创建并应用于函数调用。

但是下一部分对我来说没有意义:

>>> BigObject()
>>> undefined
>>> false

为什么 this 未定义?我假设 this 会引用一些东西——可能是全局对象窗口。不确定如何考虑这个结果。

谢谢

最佳答案

在严格模式下,当一个函数在没有上下文的情况下被调用时,thisundefined

10.4.3 Entering Function Code # Ⓣ

The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:

  1. If the function code is strict code, set the ThisBinding to thisArg.
  2. Else if thisArg is null or undefined, set the ThisBinding to the global object.
  3. Else if Type(thisArg) is not Object, set the ThisBinding to ToObject(thisArg).
  4. Else set the ThisBinding to thisArg.
  5. Let localEnv be the result of calling NewDeclarativeEnvironment passing the value of the [[Scope]] internal property of F as the argument.
  6. Set the LexicalEnvironment to localEnv.
  7. Set the VariableEnvironment to localEnv.
  8. Let code be the value of F’s [[Code]] internal property.
  9. Perform Declaration Binding Instantiation using the function code code and argumentList as described in 10.5.

提供的代码是严格代码,调用的thisArgundefined(没有为调用提供上下文)。

关于javascript - 了解 'this' 对象上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com