【问题标题】:Why the nested function doesn't becomes the property of the outer function in javascript?为什么嵌套函数不会成为javascript中外部函数的属性?
【发布时间】:2020-04-01 01:11:33
【问题描述】:

我的代码如下:

function t() {
    var name = "abc";
    bar = function() {
    console.dir(this);
    console.log('bar');
 };
};
t.foo = function() {
    console.dir(this);
    this();
    console.log('bar');
};
console.dir(t);

它给出如下输出:

ƒ t()
foo: ƒ ()
arguments: null
caller: null
length: 0
name: "t"
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: VM2091:1
[[Scopes]]: Scopes[2]

所以我们可以看到,在检查函数 t() 时,我们没有找到函数 "bar",但函数 "foo" 在函数 t() 中。我的问题是为什么函数 "bar" 不是函数 t() 的属性,而函数“foo”成为函数 t() 的属性?

【问题讨论】:

    标签: javascript javascript-objects prototypejs


    【解决方案1】:

    您可以为任何 JS 对象添加属性,包括函数。因此,当您将t 登录到控制台时,t.foo = ... 工作并显示为属性也就不足为奇了。 t.foo 指向的值是一个函数这一事实纯属偶然——它也可以是字符串、数字或其他任何东西。

    bar 这样的函数范围变量与函数体中定义的任何其他变量相同;它不是函数的属性,在函数执行之前不存在。 bar 声明了一个全局变量,因此它绑定到 window.bar 并在函数执行后持续存在。如果它是本地的,它会在函数返回时被销毁。

    您可以使用foo.barfoo 内部设置函数对象的属性,但我无法想象这会有多大用处。

    function foo() {
      foo.baz = 42;
    }
    
    foo.bar = 43;
    foo();
    console.log(foo.bar, foo.baz);

    在您的函数中,如果这些函数未绑定到任何对象,this 将是 window。如果您想将this 绑定到一个新对象并使用函数构造函数为其设置属性,请使用new operator 创建一个实例:

    function Foo() {
      this.bar = 42;
      this.quux = function () {};
    }
    
    Foo.prototype.baz = 43;
    Foo.prototype.corge = function () {};
    
    console.log(new Foo());

    这里的区别是this.函数在构造函数被调用时创建,而Foo.prototype.变量只定义一次。

    【讨论】:

      【解决方案2】:

      您正在使用类构造函数但没有绑定它,当使用构造函数时使用 this 关键字绑定变量,这就是为什么 bar 不是 t() 的属性。这样做

      function t() {
      var name = "abc";
      this.bar = function() {
      console.log(this);
      console.log('bar');
         };
      };
      

      然后创建一个新对象 var newObj=new t(); 现在从 newObj 调用函数 newObj.bar(); 这应该工作

      【讨论】:

        猜你喜欢
        • 2012-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多