1 采用匿名自执行函数定义对象
var Size = (function size() {
function constructor(w, h) {
this.w = w;
this.h = h;
}
constructor.prototype = {
toString: function () {
return "(" + this.w + ", " + this.h + ")";
},
getHalfSize: function () {
return new Size(this.w >>> 1, this.h >>> 1);
},
length: function () {
return this.w * this.h;
}
};
return constructor;
})();
此写法表示在该代码解释时就自动会执行(function size())中的方法
目的,避免污染外部的变量
2 get set访问器
var log = ['test'];
var obj = {
get latest () {
if (log.length == 0) return undefined;
return log[log.length - 1]
}
}
console.log (obj.latest); // Will return "test".