我使用下面的JS代碼玩。我有兩個問題。JavaScript原型的理解
1)爲什麼用戶不是author_1的原型?
2)爲什麼在Author.prototype author_1的重置變爲不是Authorof的Authorof後?
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"}
謝謝!
UPDATE
感謝您的幫助!但現在我無法理解AUTHOR_1如何能知道,這是一個作者
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?
你不需要'()'後兩者AUTHOR_1和AUTHOR_2'新Author'?這可能會大大改變你的結果。 –
@ScottMermelstein不,你不知道。這是可選的。 'new ConstructorFunction'的行爲與'new ConstructorFunction()'完全相同。這只是不常用的語法。 –
OP,你爲什麼要像構造函數那樣在函數內部返回this'? –