1

我试图了解执行上下文、创建阶段和执行阶段。

我想知道,有人可以帮我理解为什么,

console.log(thisFunction.ojbect1);

返回 - '未定义'。

我会认为,在创建阶段之后,当变量被分配“未定义”时,执行阶段就会运行,然后变量会被对象填充。

那么为什么我得到'object1'的'undefined',而不是整个对象呢?

非常感谢。代码如下。

var thisFunction = function(){
    var object1 = {
        firstname: 'Mark',
        printName: function(){
        console.log(this.firstname);
        }
    };

    object1.printName();
};

thisFunction();
console.log(thisFunction.object1);
4

2 回答 2

0
  1. 您需要使用来为函数对象thisFunction分配一个变量。
  2. 然后你需要使用new来创建thisFunction的对象。

这对你有效,除了:

    var thisFunction = function(){

    this.object1 = {
        firstname: 'Mark',
        printName: function(){
        console.log(this.firstname);
        }
    };

    this.object1.printName();
};

var tf = new thisFunction();
console.log(tf.object1);

使用typeof可以帮助您更好地理解对象和函数之间的区别:

console.log(typeof thisFunction);
console.log(typeof tf);
console.log(typeof tf.object1);
console.log(typeof tf.object1.firstname);

输出:

函数
对象
对象
字符串

请参阅Plunker中的此示例

于 2017-07-14T11:14:44.240 回答
0

“Object1”不是“thisFunction”的属性,所以不能调用它。“Object1”是在“thisFunction”范围内创建的变量。

您只能访问父范围的变量。

如果您想了解更多关于函数作用域的信息,这里有一些有趣的读物。

于 2017-07-14T10:51:07.387 回答