js getter setter和defineProperty兼容情况

测试数据源于: http://robertnyman.com/javascript/javascript-getters-setters.html

兼容ie9+及其他标准浏览器的写法有二:

1、

var lost = {
	loc : "Island",
	get location () {
		return this.loc;
	},
	set location(val) {
		this.loc = val;
	}
};
lost.location = "Another island";

2、

var lost = {
	loc : "Island"
};	
Object.defineProperty(lost, "location", {
	get : function () {
		return this.loc;
	},
	set : function (val) {
		this.loc = val;
	}
});
lost.location = "Another island";

发表评论

电子邮件地址不会被公开。 必填项已用*标注