2016-08-12 109 views
-1

我給一個屬性的功能,使用該功能作爲一個構造函數,像這樣:此JavaScript屬性是一個實例屬性,還是一個原型屬性?

function h(){this.a='abc';} 
h.high='2.0'; 
var hinst=new h(); 
function hasPrototypeProperty(object, name){ 
    return !object.hasOwnProperty(name) && (name in object); 
} 
console.log(h.hasOwnProperty('high')); //true 
console.log(hinst.hasOwnProperty('high'));//false 
console.log(hasPrototypeProperty(hinst, 'high'));//false 
console.log('a' in hinst); //true 
console.log('high' in hinst);//false 
console.log(hinst.prototype.constructor.high); //exception 

很奇怪,在我的測試中,「高」既不是一個實例屬性

hinst.hasOwnProperty)

或原型屬性

hasPrototypeProperty(hinst,'high')

最後一行拋出一個異常說

TypeError: Cannot read property 'constructor' of undefined

我想我對財產有一些小姐的理解,怎麼可能'不願'訪問'高'財產?

+2

'high'是構造函數的性質,因此:'hinst.constructor.high'應該返回' 「2.0」'。 'hinst.constructor.hasOwnProperty('high')'=>'true'。 – undefined

回答

1

讓我們分析一下。

這裏創建了一個構造函數。它們旨在與new操作員一起使用。一個普遍的慣例是把第一封信用於明顯的意圖。

function H(){ this.a='abc'; } 

當構造函數與new調用,類似這樣的事情發生:

(function(){ 
    var o = Object.create(H.prototype); 
    H.apply(o, arguments); 
    return o; 
}()); 

你基本上是一個新的對象({ a: 'abc' })從H.prototype對象繼承結束。也就是說,它的內部[[Prototype]]屬性指向它。

H.prototype最初是具有單一屬性的對象(constructor指向構造函數H),但您可以自由地替換或擴展它。這就是你可能想與這條線做:

H.high='2.0'; 

而是你添加屬性的構造函數H(函數是對象太)。

console.log(H.hasOwnProperty('high'));    //true 
console.log((new H()).hasOwnProperty('high'));  //false 
console.log((new H()).hasPrototypeProperty('high')); //false 

更正例子。

function H(){ this.a='abc'; } 
 
H.prototype.high='2.0'; 
 
var hinst = new H(); 
 
function hasPrototypeProperty(object, name){ 
 
    return !object.hasOwnProperty(name) && (name in object); 
 
} 
 
console.log(H.hasOwnProperty('high'));   //false 
 
console.log(hinst.hasOwnProperty('high'));  //false 
 
console.log(H.prototype.hasOwnProperty('high')); //true 
 
console.log(hasPrototypeProperty(hinst, 'high')); //true 
 
console.log('a' in hinst);      //true 
 
console.log('high' in hinst);      //true 
 
console.log(H.prototype.high);     //2.0 
 
console.log(hinst.high);       //2.0


Inheritance and the prototype chain at MDN

1

這裏hfunction類型的對象,您分配了property的對象名爲high。所以它與實例或原型無關。

+0

還是有點困惑,那我怎麼能讓「欣賞」訪問「高」屬性? – Troskyvs

+0

@Troskyvs:把它放在'h.prototype.high',而不是'h.high'!實例從原型繼承,而不是從構造函數繼承。 – Bergi

0

有一個在構造函數和原型

console.log(inst.prototype.constructor.high); // exception 
console.log(inst.constructor.high); // '2.0' 

,因爲你的構造是不是原型鏈的組成部分之間的代碼有些混亂。
當定義上構造事後性質(這是剛 功能),那麼你結束了這個

function h() { 
this.a='abc'; 
} 
h.high='2.0'; 
console.log(h); 
// => { [Function: h] high: '2.0' } 

一個弗蘭肯斯坦功能對象怪物。