有一个JS Fiddle here,您可以在不克隆到新对象的情况下替换e.target吗?
来自那个小提琴的听众在下面重复;
one.addEventListener('click', function(e) {
// default behaviour, don't modify the event at all
logTarget(e);
});
two.addEventListener('click', function(e) {
// replace the value on the same object, which seems to be read-only
e.target = document.createElement('p');
logTarget(e);
});
three.addEventListener('click', function(e) {
function F(target) {
// set another property of the same name on an instance object
// which sits in front of our event
this.target = target;
}
// put the original object behind it on the prototype
F.prototype = e;
logTarget(new F(document.createElement('p')));
});
four.addEventListener('click', function(e) {
// create a new object with the event behind it on the prototype and
// our new value on the instance
logTarget(Object.create(e, {
target: document.createElement('p')
}));
});
答案 0 :(得分:4)
我已经更新了您的小提琴(http://jsfiddle.net/8AQM9/33/),正如您所说,event.target是readonly,但我们可以使用Object.create
覆盖属性描述符。
你是在正确的方式,但是Object.create
不会只回收key: value
散列图,它会重现key: property-descriptor
你可以看到at MDN属性描述符是怎样的。
我已经取代了
Object.create(e, {
target: document.createElement('p')
});
使用
Object.create(e, {
target: {
value: document.createElement('p')
}
});
这将原型e
并修改新对象的target
属性。