Talk is cheap. Show me the code
看设计模式遇到一段代码不太理解,于是直接上电脑一敲,nice!我太喜欢这个标题了,学习好快乐!
const Book = function(name, age) {
console.log('11111', name, this instanceof Book, this);
if (this instanceof Book) {
console.log(true, name); // false "AAA"
this.name = name;
this.age = age;
} else {
console.log(false, name)
return new Book(name, age);
}
}
const a = Book('AAA', 10);
const b = new Book('BBB', 20);
console.log('222222', a, b);
说明:instanceof => 判断左边对象是否右边对象的实例,返回一个布尔值。