1.實用的遍歷寫法與工具:
(1).方法庫:
o = {};
for (p in o) {
//跳過繼承屬性
if (!o.hasOwnProperty(p))
continue;
//跳過方法
if (typeof o[p] === "function")
continue;
}
//複製屬性(覆蓋同名),不處理setter getter
function extend(o, p) {
for (prop in p) {
o[prop] = p[prop];
}
return o;
}
//複製屬性(不覆蓋同名),不處理setter getter
function merge(o, p) {
for (prop in p) {
if (o.hasOwnProperty(prop)) continue;
o[prop] = p[prop];
}
return o;
}
//刪除不需要的屬性
function restrict(o, p) {
for (prop in o) {
if (!(prop in p))
delete o[prop];
}
return o;
}
//刪除同名屬性
function substract(o, p) {
for (prop in p) {
delete o[prop];
}
return o;
}
//返回一個合成的新對象
function union(o, p) {return extend(extend({}, o), p);}
//返回一個新對象, 包含兩個對象的公共屬性
function intersection(o, p) {return restrict(extend({}, o), p);}
//返回自有屬性的屬性名數組
function keys(o) {
if (typeof o !== "object") throw new TypeError();
var result = [];
for (var prop in o) {
if (o.hasOwnProperty(prop)) {
result.push(prop);
}
return result;
}
}
(2).僅ECMAScript5:
Object.keys和Object.getOwnPropertyNames方法分別返回對象可枚舉的和所有自有屬性名的集合。
2.getter和setter:
var p = {
x: 1.0,
y: 1.0,
//this指向本對象
get r() {return Math.sqrt(this.x * this.x + this.y * this.y)},
set r(newValue) {}
};
console.log(p.r);