function createPerson(name) {
const o = {};
o.name = name;
o.getName = function() {
console.log(this.name);
}
return o;
}
const person1 = createPerson(‘lazy‘);
person1.getName(); // lazy
console.log(person1.name); // lazy
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
console.log(this.name)
}
function Car(model) {
this.model = model;
}
Car.prototype.getModel = function() {
console.log(this.model)
}
function create(type, param) {
if(this instanceof create) { // 判断后面的构造函数的原型,是不是前面对象的原型链里
return new this[type](param);
}else {
return new create(type, param);
}
}
create.prototype = {
person: Person,
car: Car
}
const person1 = new create(‘person‘, ‘张三‘);
person1.getName(); // 张三
const car1 = create(‘car‘, ‘Benz‘);
car1.getModel(); // Benz
new create(‘person‘, ‘张三‘) 发生了什么?
new thistype 发生了什么?
原文:https://www.cnblogs.com/landuo629/p/14318455.html