2017-05-04 30 views
0

在通過JavaScript學習JavaScript權威指南,只見方法是屬性的子集嗎?

當屬性的值是一個函數,我們稱之爲方法。

Q1。方法是屬性的子集嗎?


Q2。當聲明一個變量,如字符串和數字(​​NOT Object)時,它是從String還是Number對象繼承屬性?

+1

屬性是屬性。屬性的值,如變量的值,可以是對對象,數字,字符串,「null」或對函數的引用(引用對象的特例)或其他各種引用的東西。 – Pointy

回答

-2

Q1。方法是屬性的子集嗎?

是的,在javascript中,任何對象變量都是屬性。如果它的價值是功能,它被稱爲一種方法。一般來說,對象變量被稱爲領域屬性,而性能行爲像包括虛擬變量得到設置對象的方法來訪問和修改一些私人領域。在javascript中,我們可以增強此行爲的對象變量,請參閱定義獲取器和設置器here。第二季度銷售價格指數爲:

Q2。當聲明一個變量,如字符串或數字(NOT Object)時,它是從String還是Number對象繼承屬性?

變量的聲明號只定義範圍和默認其類型是undefined

function question() { 
    var answer; // answer is undefined type with question scope and undefined value 
    answer = 42; // now answer is number type 
} 

數和字符串是原始值,它們不包含任何成員。但是,如果訪問相應對象類型(Number或String)的成員,則會在窗簾後創建一個臨時對象,訪問該成員,然後臨時對象將消失。

var b = "hello"; // b does not contain indexOf() method 
b.indexOf("lo"); // indexOf() is invoked on temporary created object 
"hello".indexOf("lo"); // same effect 
var c = new String("hello"); // c contains indexOf() method, greater footprint than b 
c.indexOf("lo"); // temporary object is not created, more effective 

console.log(b, typeof b); 
// "hello" 
// string 
console.log(c, typeof c); 
// String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", length: 5, [[PrimitiveValue]]: "hello"} 
// object 
// also contains __proto__ - prototype of the String object 
console.log(b==c); 
// true (comparison operator is overloaded) 
console.log(b===c); 
// false (the type does not match) 

正如你所看到的,如果你不需要成員,創建一個原始值更有效。但是如果你使用成員,創建一個對象會更有效,在這種情況下,這些屬性將被繼承。

+0

什麼是「屬性成員」?從來沒有聽說過。 – Bergi

+0

@Bergi它們是[屬性描述符](https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)的對象,因此鍵是成員。至少這是我的理解。如果有任何誤用的術語,請啓發我改進這個答案。 –

+0

正確的術語是它們屬性的屬性*。只有*屬性描述符*是一個對象,屬性本身不是。但是我不明白這些與屬性 - 方法問題有什麼關係。 – Bergi

1

Q1。方法是屬性的子集嗎?

是的。當一個屬性的值是一個函數(或者,嚴格來說,是一個函數的引用)時,它通常被稱爲對象的一個​​方法。它也推斷該方法應該被調用來設置其對象:

var global = this; 
 
var obj = { 
 
    fn: function() { 
 
    console.log('this is ' + (this == obj ? 'obj' : 
 
     this == global? 'global' : this) 
 
    ); 
 
    } 
 
}; 
 

 
// Call as method of obj 
 
obj.fn(); 
 

 
// Call as plain function 
 
var f = obj.fn; 
 
f();

Q2。當變量像string和number(NOT Object)一樣被聲明時,它是否繼承了String,Number Object的屬性?

變量沒有類型,它們的值是。聲明變量只是將其作爲相關上下文中的參考(請注意var的行爲與letconst的行爲不同)。

它可能會出現一個變量有一個類型,但它是有類型的值:

var a; 
 
console.log('a is : ' + typeof a); // undefined 
 
a = "A"; 
 
console.log('a is : ' + typeof a); // string 
 
a = 5; 
 
console.log('a is : ' + typeof a); // number