Javascript代码输出示例

javascript output example from code

本文关键字:输出 代码 Javascript      更新时间:2023-09-26

我是javascript新手,想知道代码的输出是什么:

var myObject = {
    foo: "bar",
    func: function() {
    var self = this;
    console.log("outer func:  this.foo = " + this.foo);
    console.log("outer func:  self.foo = " + self.foo);
    (function() {
        console.log("inner func:  this.foo = " + this.foo);
        console.log("inner func:  self.foo = " + self.foo);
    }());
    }
};

还不知道foo是怎么工作的

Javascript中的每个函数调用都会根据函数被调用的方式重置this的值(参见this被控制的五种方式的答案)。

因此,当您使用IIFE结构(function() { ... })()(这只是一个普通的函数调用)时,this的值被重置为window对象或undefined(如果在严格模式下运行)。

所以,如果你不是在strict模式下运行,那么内部函数中的this.foo引用将试图访问window.foo,这可能是undefined

并且,当我在不处于严格模式的jsFiddle中运行此命令并实际调用myObject.func()时,控制台显示:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

一个额外的console.log()语句确认在内部函数this === window,当然,window.fooundefined


如果您在严格模式下运行代码,那么调用myObject.func()将生成Uncaught TypeError: Cannot read property 'foo' of undefined错误,因为在内部函数中,this === undefined .