我玩下面的 JS 代码。我有两个问题。
1)为什么User不是author_1的原型?
2) 为什么在Author.prototype 重置后author_1 变成了不是Author 的instance?
function User(_fname){
this.fname = _fname;
return this;
}
function Author(){
this.book = "Magick of JS";
return this;
}
Author.prototype = new User('John');
author_1 = new Author;
console.log("=======================");
console.log(author_1 instanceof Author); // true
console.log(author_1 instanceof User); // true
console.log(User.isPrototypeOf(author_1)); // false (>>>> 1) WHY? <<<<)
console.log(author_1.constructor); // User(_fname)
console.log(author_1.__proto__); // User { fname="John"}
console.log(Object.getPrototypeOf(author_1)); // User { fname="John"}
console.log(author_1.constructor.prototype); // User {}
Author.prototype = new User('Alex');
author_2 = new Author;
console.log("=======================");
console.log(author_1 instanceof Author); // false (>>>> 2) WHY? <<<<)
console.log(author_1 instanceof User); // true
console.log(User.isPrototypeOf(author_1)); // false
console.log(author_1.constructor); // User(_fname)
console.log(author_1.__proto__); // User { fname="John"}
console.log(Object.getPrototypeOf(author_1)); // User { fname="John"}
console.log(author_1.constructor.prototype); // User {}
console.log("=======================");
console.log(author_2 instanceof Author); // true
console.log(author_2 instanceof User); // true
console.log(User.isPrototypeOf(author_2)); // false
console.log(author_2.constructor); // User(_fname)
console.log(author_2.__proto__); // User { fname="Alex"}
console.log(Object.getPrototypeOf(author_2)); // User { fname="John"}
console.log(author_2.constructor.prototype); // User {}
console.log("=======================");
console.log(author_1); // User {book: "Magick of JS", fname: "John"}
console.log(author_2); // User {book: "Magick of JS", fname: "Alex"}
谢谢!
更新
感谢帮助!但是现在我不明白 author_1 怎么知道它是 Author
function log(){ console.log.apply(console, arguments) }
function User(_fname){
this.fname = _fname;
return this;
}
function Author(){
this.book = "Magick of JS";
return this;
}
Author.prototype = new User('John');
author_1 = new Author;
log(author_1); // User { book="Magick of JS", fname="John"}
log(author_1.__proto__); // User { fname="John"}
log(author_1.constructor); // User(_fname)
log(author_1 instanceof Author); // true
// How author_1 kowns that it's an Author? Where is property?
// Can I find it in web inspector? Or it's hidden value?