js自定义一个对象,并为对象添加三个事件,并移除其中一个事件
时间: 2024-01-15 16:02:35 浏览: 32
好的,这里是一个 JavaScript 自定义对象的示例代码,它包含三个事件 `onStart`、`onUpdate` 和 `onStop`,并演示了如何移除 `onUpdate` 事件:
```javascript
// 定义自定义对象
function CustomObject() {
this.events = {
'onStart': [],
'onUpdate': [],
'onStop': []
};
}
// 添加事件
CustomObject.prototype.addEvent = function(event_name, event_func) {
if (this.events[event_name]) {
this.events[event_name].push(event_func);
}
};
// 移除事件
CustomObject.prototype.removeEvent = function(event_name, event_func) {
if (this.events[event_name]) {
var index = this.events[event_name].indexOf(event_func);
if (index !== -1) {
this.events[event_name].splice(index, 1);
}
}
};
// 触发事件
CustomObject.prototype.triggerEvent = function(event_name) {
if (this.events[event_name]) {
this.events[event_name].forEach(function(event_func) {
event_func();
});
}
};
// 创建自定义对象
var obj = new CustomObject();
// 添加事件
function startFunc() {
console.log('Object started');
}
function updateFunc() {
console.log('Object updated');
}
function stopFunc() {
console.log('Object stopped');
}
obj.addEvent('onStart', startFunc);
obj.addEvent('onUpdate', updateFunc);
obj.addEvent('onStop', stopFunc);
// 移除事件
obj.removeEvent('onUpdate', updateFunc);
// 触发事件
obj.triggerEvent('onStart');
obj.triggerEvent('onUpdate');
obj.triggerEvent('onStop');
```
运行上述代码,控制台将输出以下结果:
```
Object started
Object stopped
```
可以看到,我们成功地创建了一个自定义对象,并成功地添加了三个事件。然后,我们移除了其中一个事件,最后触发了所有事件并且只有两个事件被执行了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)