在three.js中,發現了大量使用Object.assign和Object.create方法,并且很多構造函數都有繼承EventDispatcher,現針對EventDispatcher方法研究一下
1.源碼
function EventDispatcher() {} // 構造函數
Object.assign(EventDispatcher.prototype, {
addEventListener: function (type, listener) {
if (this._listeners === undefined) {
this._listeners = {};
}
var listeners = this._listeners;
if (listeners[type] === undefined) {
listeners[type] = [];
}
if (listeners[type].indexOf(listener) === -1) {
listeners[type].push(listener);
}
},
hasEventListener: function (type, listener) {
if (this._listeners === undefined) {
return false;
}
var listeners = this._listeners;
return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
},
removeEventListener: function (type, listener) {
if (this._listeners === undefined) {
return;
}
var listeners = this._listeners;
var listenerArray = listeners[type];
if (listenerArray !== undefined) {
var index = listenerArray.indexOf(listener);
if (index !== -1) {
listenerArray.splice(index, 1);
}
}
},
dispatchEvent: function (event) {
if (this._listeners === undefined) {
return;
}
var listeners = this._listeners;
var listenerArray = listeners[event.type];
if (listenerArray !== undefined) {
event.target = this;
var array = listenerArray.slice(0);
for (var i = 0, l = array.length; i < l; i++) {
array[i].call(this, event);
}
}
}
});
function Texture() {} // 構造函數
Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
test: function() {
console.log('test')
}
})
2.測試代碼
const tt = new Texture()
console.log('tt', tt)
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQDOxEzX3xCZlhXam9VbsUmepNXZy9CXwJWZ3xCdh1mcvZ2Lc1zaHRGcWdUYuVzVa9GczoVdG1mWfVGc5RHLwIzX39GZhh2csATMflHLwEzX4xSZz91ZsAzMfRHLGZkRGZkRfJ3bs92YskmNhVTYykVNQJVMRhXVEF1X0hXZ0xCNx8VZ6l2cssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL4ADOxU2M4YWMilTZ0MTYyQTMyEGZyIGO3M2N3ETN5cDMkRTY1YzLcJDMyIDMy8CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
3.核心代碼說明
如果作如下代碼修改
4.總結
- three.js中很多構造函數都會繼承EventDispatcher構造函數
- Object.assign方法的使用
- Object.create方法的使用
- three.js中的事件監聽和其他的架構都是類似的,例如jQuery也是如此來處理,都是相同的原理