我想在jQuery闭包中看到窗口属性“ otherName”描述符。但
    进jQuery闭包'otherName'描述符显示未定义,我想可能
    getOwnPropertyDescriptor()没有获得窗口对象。我对吗?如果我用
    此代码以纯js语言编写,

var otherName = "ckMe";
var result = Object.getOwnPropertyDescriptor(window, "otherName");
console.log(result);
// Object { value: "ckMe", writable: true, enumerable: true, configurable:
//false }


这可以。但是当在jQuery中使用此代码时,我得到了result = undefined。

(function ($) {
  $(window).on("load", function (event) {
    var otherName = "ckMe";
    var result = Object.getOwnPropertyDescriptor(window, "otherName");
    console.log(result);//undefined
  });
}(jQuery));


或者,如果我使用此代码相同的结果,则未定义。

(function ($) {
  $(function () {
    var otherName = "ckMe";
    var result = Object.getOwnPropertyDescriptor(window, "otherName");
    console.log(result);//undefined
  });
}(jQuery));


我想在jQuery闭包中使用此代码,因为我的所有代码都在其中。一世
已经在Google上搜索了此问题,但没有得到最好的结果
解。请帮我。谢谢大家。
抱歉,如果我有任何问题。

最佳答案

在您的后两个代码块中,otherName不是window的属性。 window仅在全局范围内获取var声明的属性。在您的后两个代码块中,var声明不在全局范围内,因此otherName不是任何东西的属性¹,它只是一个局部变量。它们没有属性描述符,因为它们不是属性。



¹“不是任何东西的属性”-用规范术语来说,局部变量是Lexical Environment对象上的绑定。绑定有点像属性,但是它们不是属性(就JavaScript的对象属性而言),并且它们没有属性描述符(也不能直接访问Lexical Environment对象-实际上,它可能不会实际上存在于任何特定的JavaScript引擎中)。

10-01 14:05
查看更多