2016-11-25 53 views
1

我一直在嘗試使用object.defineproperty編寫getter和setter,但是不能。我一直在嘗試這個例子,但由於沒有定義firstName屬性而引發錯誤。有人可以幫我這個如何在javascript中使用object.define屬性來定義getter和setter

function person(fName, lName) { 
 

 

 
    Object.defineProperty(this, 'firstName', { 
 
    get:function() { return firstName; }, 
 
    set:function(newValue){firstName=newValue;} 
 
}); 
 
} 
 
var p1=person("xyz","abc"); 
 
console.log(p1.firstName);

感謝

+0

在哪裏使用'fName'和'lName'? Uhuh,你沒有。你怎麼期望傳遞一個價值,而不是通過它? ;-) –

+0

我的想法是在person對象中創建一個firstName屬性,它應該有fName值 – Geeky

+0

找不到我怎麼做的方法 – Geeky

回答

2

你應該newPerson創建Person實例。正如你所看到的,你可以簡單地使用你傳遞給你的getter和setter的構造函數的變量。
我特意命名了構造函數參數,以查看所有變量如何一起玩。

在你的getter中,你返回firstNameFromConstructor變量,或者做一些處理然後返回它。
在你的setter中,你可以改變firstNameFromConstructor變量的值。

function Person(firstNameFromConstructor, lastNameFromConstructor) { 
 
    Object.defineProperty(this, 'firstName', { 
 
     get:function() { return firstNameFromConstructor; }, 
 
     set:function(newFirstName){ firstNameFromConstructor = newFirstName;} 
 
    }); 
 
    Object.defineProperty(this, 'lastName', { 
 
     get:function() { return lastNameFromConstructor; }, 
 
     set:function(newLastName){ lastNameFromConstructor = newLastName;} 
 
    }); 
 
} 
 

 
var p1= new Person("xyz","abc"); 
 
console.log(p1.firstName); 
 
p1.firstName = 'zyx' 
 
console.log(p1.firstName);

+0

這是基於[此mdn頁面](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Custom_Setters_and_Getters)。 – sniels

0

您需要保存到你傳入構造器的參數引用,這樣你就可以得到/集T實例化後的下襬。

function person(fName, lName) {  
    Object.defineProperty(this, 'firstName', { 
    get: function() { return this._firstName; }, 
    set: function (newValue) { this._firstName = newValue; } 
    }); 

    Object.defineProperty(this, 'lastName', { 
    get: function() { return this._lastName; }, 
    set: function (newValue) { this._lastName = newValue; } 
    }); 

    this.firstName = fName; 
    this.lastName = lName; 
} 

var p1 = new person("xyz", "abc"); 
console.log(p1.firstName); 
+0

這隻適用於二傳手。如果單獨使用,吸氣劑不需要這個。 –

2

在您的getter你回來firstName,但目前尚不能確定,所以正上方Object.defineProperty聲明firstNamefName參數分配給它。

而且,當你聲明P1使用new操作讓你person構造的作品,並分配"xyz"firstName財產。

所以,試試這個:

function person(fName, lName) { 
 

 
    var firstName = fName; 
 

 
    Object.defineProperty(this, 'firstName', { 
 

 
    get:function() { return firstName; }, 
 
    set:function(newValue){firstName=newValue;} 
 

 
}); 
 

 
} 
 

 
var p1 = new person("xyz","abc"); 
 

 
console.log(p1.firstName); 
 

 
p1.firstName = "abc"; 
 

 
console.log(p1.firstName);

相關問題