我最近一直在阅读"有效的JavaScript",我遇到了这个问题.
作者解释了如何使构造函数与新的无关,因为如果开发人员忘记使用'new'关键字调用Constructor,'this'指的是'Window'.那讲得通.令我困惑的是他实施的目的.
他建议像这样设置你的构造函数.
var Person = function(name, age){
var that = this instanceof Person ? this : Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
Run Code Online (Sandbox Code Playgroud)
那讲得通.您检查'this'是否是Person的实例,这意味着它是使用'new'关键字调用的.如果不是,则创建一个与"this"相同的新Object并返回该对象.
我的问题是这个.如果你正在设置一个与'this'完全相同的新Object,那么我们不能再担心是否通过前面的'this'调用了构造函数而只是创建了新对象.
var Person = function(name, age){
var that = Object.create(Person.prototype);
that.name = name;
that.age = age;
return that;
}
Run Code Online (Sandbox Code Playgroud)
为什么不担心'this'和'new',为什么不总是像上面那样创建我们的构造函数?
为什么不担心'this'和'new',为什么不总是像上面那样创建我们的构造函数?
因为只写更简洁
function Person(name, age) {
this.name = name;
this.age = age;
}
Run Code Online (Sandbox Code Playgroud)
new是之前发明的Object.create(在旧版浏览器中不可用)并成为标准模式.大多数人都习以为常,他们不打算包括if (!(this instanceof Person)) return new Person(name, age)支票.
如果你正在设置一个与'this'完全相同的新Object,那么我们不能再担心是否通过前面的'this'调用了构造函数而只是创建了新对象.
不,您并不总是知道如何创建新对象.this instanceof Person对于继承的任何其他东西也是如此Person.prototype,并且允许类继承:
function Employee(name, age, salary) {
Person.call(this, name, age);
this.salary = salary;
}
Employee.prototype = Object.create(Person.prototype);
Run Code Online (Sandbox Code Playgroud)
该Person.call(this)如果选择总是返回一个新的对象将是不可能的.