Javascript中一些可能是用较少的语法

set/get

1
var data = {
	items: ['a', 'b', 'c'],
	get length () {
		return this.items.length;
	},
	set first (val) {
		this.items[0] = val;
	}
};
console.log(data.length); // 3
data.length = 4; // 严格模式下报错:Uncaught TypeError: Cannot set property length of #<Object> which has only a getter(…)
console.log(data.first = 'd');
console.log(data.items); // ["d", "b", "c"]

var MyDate = function() {}

defineGetter/defineSetter

1
var data = {
	items: ['a', 'b', 'c']
};
data.__defineGetter__('length', function() {return this.items.length;});
data.__defineSetter__('first', function(val) {this.items[0] = val;})
console.log(data.length); // 3
console.log(data.first = 'd');
console.log(data.items); // ["d", "b", "c"]

Object.freeze

将某个对象冻住,好形象。

1
var a = {a:1, b: 2}; 
Object.freeze(a); 
a.c =3;
console.log(a); // {a: 1, b: 2}

Object.defineProperty

1
var obj1 = {};
Object.defineProperty(obj1, "x", { value: 42, writable: false });
obj1.x = 9; // 严格模式下抛出TypeError错误
console.log(obj1.x); // 42

Object.preventExtensions

1
// 给不可扩展对象的新属性赋值
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = "ohai"; // 严格模式下抛出TypeError错误
console.log(fixed); // {}

Function

1
console.log(new Function('a', 'b', 'return a + b;')(1, 2)) // 3
文章目录
  1. 1. set/get
  2. 2. defineGetter/defineSetter
  3. 3. Object.freeze
  4. 4. Object.defineProperty
  5. 5. Object.preventExtensions
  6. 6. Function
,