调用构造函数 |为什么 "this" 关键字 return 未定义?

Calling a constructor function | why does "this" keyword return undefined?

我正在研究对象和构造函数,很好奇为什么我不能执行:person(5,10)。参数被传递给 person 函数,但随后变量赋值消失,我在 chrome 中得到 "cannot set property "age" of undefined" 错误。

"use strict"

function person(age, height){
this.age = age;
this.height = height;
this.calculate = function(){
     var newHeight = this.height * 2;
     console.log(newHeight);
    }
}
person(5,10);

I get the "cannot set property "age" of undefined" error in chrome.

当你在strict mode, this中调用函数时是undefined。看来您想将函数作为构造函数调用, new:

new person(5, 10)

Learn more about constructors.


注意:约定是构造函数的名称大写。

之所以会产生混淆,是因为函数既可以用作可调用函数,也可以用作对象构造函数。 好的做法是不要混淆这两种形式,这意味着构造函数不应用作可调用函数。 一般来说,构造函数的首字母大写(只是按照惯例给代码的 reader 一个提示)。 基于对象的语言通常隐式提供对调用方法的对象的引用。在 Javascript 中,此引用是函数内的 "this" 关键字。 考虑以下代码。

var obj = {
    sum: 0,
    add: function(increment) {
        this.sum += increment;
        return this.sum;
    }
};

当我们调用 obj.add(2) 时,任何其他基于对象的语言中的解释器或编译器将对方法 add 进行内部调用,如下所示

add(arguments..., [this=obj]) {
    //this is the obj reference inside the method
}
add(arguments, obj);

以上只是一个伪代码,最后一个参数对我们是隐藏的,我们不需要显式传递它,这个参数是对调用add()方法的实际对象的引用并且可用通过 "this" keyworkd.

一般来说,当我们在 Object 范围之外声明一个函数时,它会成为全局对象(通常是 window 对象)的方法(如果没有嵌套在另一个函数中,则已编辑**)。所以它的调用将传递全局对象作为 "this" 引用。在严格模式下,默认全局对象是未定义的,任何必须在 window 或全局对象上完成的操作都将显式完成。以免我们无意中修改了全局对象。

当我们像下面这样调用一个函数作为构造函数时

var p1 = new Person();

解释器将执行类似于

的代码
var newObj = new Object();
Person(arguments..., [this=newObj]) {
    //this is the newObj reference inside the method
    return this;
}
Person(arugments..., newObj);

我希望现在更清楚了。