Decorator 与 OOP
关于 Object.defineProperty
The
Object.defineProperty()
method defines a new property directly on an object, or modifies an exisiting property on an object, and returns the object.
js
Object.defineProperty(obj, prop, descriptor);
obj
The object on which to define the property.prop
The name of the property to be defined or modified.descriptor
The descriptor for the property being defined or modified.configurable
是否可删除目标属性或修改属性以下特性 (writable
|configurable
|enumerable
)enumerable
是否能在for-in
循环中遍历出来或在Object.keys
中列举出来value
get
set
return
The object that was passed to the function.
上面不想翻译了,详见 MDN Web Docs 。
借助 Object.defineProperty
的一个伪的双向绑定实现:
```js const model = {}; const view = document.createElement('input');
Object.defineProperty(model, 'value', { get: function() { return this.value; }, set: function(val) { this.value = val; view.value = val; }, });
view.addEventListener('change', function(e) { model.value = e.target.value; });
document.body.appendChild(view); ```
-->loading...
还没有人评论...