方法是與對象,或者說相關聯(lián)的函數(shù),一種方法是一個對象,它是函數(shù)的一個屬性。
方法的定義方式與常規(guī)函數(shù)的定義方式相同,不同之處在于必須將它們分配為對象的屬性。
為了檢索對象方法,您將以與調用常規(guī)函數(shù)相同的方式對其進行調用,只是將其附加到對象變量上。
// 創(chuàng)建對象
var user = {
firstName: "Seagull",
lastName : "an",
age : 22,
location : "New Delhi",
getName : function() {
return this.firstName + " " + this.lastName;
}
};
//訪問getName()方法
user.getName();測試看看?/?如果訪問不帶()括號的方法,它將返回函數(shù)定義:
user.getName;測試看看?/?
JavaScript有一個特殊的關鍵字this,您可以在方法中使用它來引用當前對象。
您可能已經(jīng)注意到我們的方法有些奇怪。以這個為例:
getName: function() {
return this.firstName + " " + this.lastName;
}this關鍵字是指代碼被寫入內部當前對象-所以在這種情況下,this等同于user。
換句話說,this.firstName表示此對象的firstName屬性。
您可以在JS關鍵字教程JS中了解有關該this關鍵字的更多信息。
為了向對象添加新方法,您可以使用賦值運算符(=)將新函數(shù)分配給屬性。
本示例向用戶對象添加“ greet”方法:
user.greet = function() {
return "Hello World";
};測試看看?/?ECMAScript 5(2009)引入了Getters和Setters。
getter是一種獲取特定屬性值的方法。
setter是一種設置特定屬性值的方法。
您可以在支持添加新屬性的任何預定義核心對象或用戶定義對象上定義getter和setter。
本示例使用get loc屬性作為location屬性的值:
//創(chuàng)建一個對象
var user = {
firstName: "Seagull",
lastName : "Anna",
age : 22,
location : "New Delhi",
get loc() {
return this.location;
}
};
//顯示來自對象的數(shù)據(jù)
document.getElementById("para").innerHTML = user.loc;測試看看?/?本示例使用set loc屬性作為location屬性的值:
// 創(chuàng)建對象
var user = {
firstName: "Seagull",
lastName : "Anna",
age : 22,
location : "New Delhi",
set loc(x) {
this.location = x;
}
};
// 使用setter設置對象屬性
user.loc = "Goa";
// 顯示來自對象的數(shù)據(jù)
document.getElementById("para").innerHTML = user.location;測試看看?/?以下兩個示例顯示了function 和 getter之間的區(qū)別:
//創(chuàng)建對象
var user = {
firstName: "Seagull",
lastName : "Anna",
age : 22,
location : "New Delhi",
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// 顯示來自對象的數(shù)據(jù)
document.getElementById("para").innerHTML = user.fullName();測試看看?/?// 創(chuàng)建對象
var user = {
firstName: "Seagull",
lastName : "Anna",
age : 22,
location : "New Delhi",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
//顯示來自對象的數(shù)據(jù)
document.getElementById("para").innerHTML = user.fullName;測試看看?/?示例1 將fullName作為函數(shù)訪問:user.fullName()。
示例2 將fullName作為屬性訪問:user.fullName。
使用Getters 和 Setters:
它提供了更簡單的語法
它允許屬性和方法的語法相同
它可以確保更好的數(shù)據(jù)質量
對于后端處理很有用
Object.defineProperty()方法還可以用于添加Getter和Setter。
Object.defineProperty(object, property, {value : value})讓我們以“計數(shù)器”對象為例:
var counter = {i : 0};
Object.defineProperty(counter, "increment", {
get: function() {this.i++;},
});
Object.defineProperty(counter, "decrement", {
get: function() {this.i--;},
});
Object.defineProperty(counter, "reset", {
get: function() {this.i = 0;},
});
Object.defineProperty(counter, "add", {
set: function (value) {this.i += value;}
});
Object.defineProperty(counter, "subtract", {
set: function (value) {this.i -= value;}
});
counter.reset;
counter.add = 25;
counter.increment;測試看看?/?