index.js
// 方法1:严格模式
function Person(name) {
"use strict";
this.name = name;
}
const lilei = Person("李雷"); // Error
console.log(lilei.name);
index.js
// 方法2:判断添加
function Person(name) {
if (!(this instanceof Person)) {
return new Person(...arguments);
}
this.name = name;
}
const lilei = Person("李雷");
console.log(lilei.name); // '李雷'
index.js
// 方法3:new.target
function Person(name) {
if (!new.target) {
return new Person(...arguments);
}
this.name = name;
}
const lilei = Person("李雷");
console.log(lilei.name); // '李雷'