2016-08-12 97 views
-1

從ObjectConstructor.defineProperty我看到這個函數的第一個參數是(o:any),它表示任何對象。是否Javascript'Object.defineProperty'只接受原型對象作爲參數

於是,我就定義屬性兩個構造函數和實例,象下面這樣:

function h(){this.a='abc';} 
h() 
console.log(exports.a); 
Object.defineProperty(h,'b');//TypeError 
var hinst=new h(); 
Object.defineProperty(hinst,'b');//TypeError 
Object.def 

事實上,無論Object.defineProperty語句將拋出運行時異常,說

TypeError: Property description must be an object: undefined. Why this error happen, any indications, or any de factor restrictions about how Object.defineProperty should be used?

+1

[對象。 defineProperty(obj,prop,descriptor)](https://developer.mozilla.org/en/docs/Web/JavaScript/Refe rence/Global_Objects/Object/defineProperty) –

+0

看看[文檔](https://msdn.microsoft.com/en-us/library/dd548687(v = vs.94).aspx) –

+0

「*我看到這個函數的第一個參數... *「 - 你在讀什麼文檔?它對第二個參數有什麼看法? – Bergi

回答

2

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object. More info here .

正確的語法是:

Object.defineProperty(obj, prop, descriptor)

你的腳本,而不是從你的代碼錯過descriptor,例如:

Object.defineProperty(h,'b');

下面的如何,而應使用一個樣本:

function h() { 
 
    this.a = 'abc'; 
 
} 
 
Object.defineProperty(h, 'b',{ 
 
    value: 37, 
 
    writable: true, 
 
    enumerable: true, 
 
    configurable: true 
 
}); 
 
var hinst = new h(); 
 
Object.defineProperty(hinst, 'b',{ 
 
    value: 37, 
 
    writable: true, 
 
    enumerable: true, 
 
    configurable: true 
 
}); 
 
console.log(hinst);

相關問題