2015-09-26 29 views
0

我對Javascript的原型屬性感到困惑。 請參閱下面的代碼。Javascript Prototype屬性:基於原型的繼承

var s = 12; 
var s1 = new String(); 

console.log(s.constructor); // Outputs: Number() { [native code] } 
console.log(s instanceof String); // Outputs: false 
console.log(s instanceof Object); // Outputs: false 
//console.log(toString() in s); 
console.log(s.isPrototypeOf(Object)); // Outputs: false 
//console.log(s.prototype.isPrototypeOf(Object)); 

console.log(s.hasOwnProperty ("toString")); // Outputs: false 

console.log(s.toString()); // // Outputs: 12 
// My Question is how does toString() function is been called, where does it falls int the prototype chain. Why is it not showing undefined. 

console.log(s1.constructor); // Outputs: Number() { [native code] } 
console.log(s1 instanceof String); // Outputs: true 

據我所知,當我們創建通過使用對象{}或構造(新的字符串())的上方,它從Object.prototype中繼承。這就是爲什麼console.log(s1 instanceof String); // Outputs: true,因此我們能夠在s1上調用toString()。但我很困惑發生在var x = "someString" or var x = something.的情況下

感謝您的時間。

回答

1

字符串原始值(如"hello world")與String對象之間存在差異。原始類型—字符串,數字,布爾值—不是對象。

當原始值是用於狀物體,與.[]運營商,運行時隱式地包裝在通過相應的構造(StringNumberBoolean)對象的值。原始值沒有屬性,但由於該自動換行,你可以做類似於

var n = "hello world".length; 

它工作。

+0

謝謝,現在有道理,還有一個問題,如果我說的premitive類型根本沒有原型屬性或沒有屬性,它是正確的,它只是隱式轉換,允許它們調用所需的屬性,如果適用。 – nitte93user3232918

+0

@ nitte93user3232918是的,這是正確的 - 原始值不是對象,所以它們沒有對象具有的東西(如原型)。 – Pointy