gpt4 book ai didi

Javascript:函数作为属性

转载 作者:行者123 更新时间:2023-12-03 10:14:22 28 4
gpt4 key购买 nike

假设我有这样的代码:

function on(loc,type,func){
loc.addEventListener(type, function(e){
func(e);
});
}

如果我这样调用它:

on(document.getElementById('test'),"click",function(){
alert('You clicked!');
});

它可以工作,但我希望能够像这样调用 on 函数:

document.getElementById('test').on('click', function(){
alert('You clicked!');
});

我怎样才能让它像这样被调用?

最佳答案

正如已经指出的,DocumentElement 没有 .on() 方法。然而!

但是,您可以通过 extending the prototype 添加一个,添加一个新属性并使您的函数在所有元素上可用。这非常简单(我稍后将提供一个简单的示例),但它也是 widely considered to be a bad practice 。因此,在尝试之前,请了解 Javascript 绝对可以使其成为可能……但这并不意味着这是一个好主意。

现在,这个例子:

Element.prototype.test = function() {
console.log("Successfully extended the prototype of a native object!");
}

document.getElementById("footer").test();

关于Javascript:函数作为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957336/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com