gpt4 book ai didi

javascript - 每个对象都应该有一个方法 'addEventListener' 吗?

转载 作者:行者123 更新时间:2023-11-30 18:37:59 25 4
gpt4 key购买 nike

我需要一个函数来生成 m 和 n 之间的伪随机整数,所以我想,“我知道,我将使用类似于 Python 的 randrange 方法扩展 Math”。

Math.constructor.prototype.rand = function rand(min, max) {
return min + Math.floor(Math.random() * (max + 1 - min));
};

这似乎可行,但是当我将它放入我的集成代码中时,我遇到了多个错误消息问题,例如“[that function] has no method 'addEventListener'”。

我的问题的要点是:我在这里扩展 Math 的方式是否存在根本性错误?该函数是否应该有这样的方法,如果没有,为什么 jwplayer 要求它?

我在下面附上了更多详细信息,但如果您已经厌烦并想开始假设答案,则可以跳过其余部分。


当我去测试集成代码时,我看到了这个错误:

jwplayer.js:1 Uncaught TypeError: Object function rand(min, max) {
return min + Math.floor(Math.random() * (max + 1 - min));
} has no method 'addEventListener'
jwplayer.js:1 a.plugins.pluginloader.load
jwplayer.js:1 a.embed
jwplayer.js:1 b.api.setup
script.js:155 (anonymous function)
jquery-1.6.4.js:660 jQuery.extend.each
jquery-1.6.4.js:274 jQuery.fn.jQuery.each
script.js:150 jQuery.click.window.Modernizr.input.required
jquery-1.6.4.js:1016 jQuery.extend._Deferred.deferred.resolveWith
jquery-1.6.4.js:437 jQuery.extend.ready
jquery-1.6.4.js:923 DOMContentLoaded

这是上面提到的来自 script.js 的片段:

// Setup the video player:
$("video").each(function (i, e) {
// Switching out ids like this is a horrible hack,
// but apparently it's the only way jwplayer will load.
var oldId = $(e).attr('id');
$(e).attr("id", "tmpVideoSetup");
jwplayer("tmpVideoSetup").setup({
flashplayer: window.CDN + "/js/libs/mediaplayer-5.7-licensed/player.swf",
levels: [
// TODO: set this up to dynamically choose the videos to play.
{ file: window.CDN + "/videos/LK_About.mp4" },
{ file: window.CDN + "/videos/LK_About.wmv" }
]
});
$(e).attr("id", oldId);
});

当我删除视频加载代码时,其他一切都按预期运行。

最佳答案

为什么要把它附加到 Math 上呢?如果您打算这样做,Math.rand = ... 有什么问题?

Math 对象不应以原型(prototype)方式扩展,因为它是“静态”类型。您不能实例化它(即用 new 调用它)。这是一个特例。所有其他类型都是“非静态”的。尽管这不足为奇,Math 只是静态方法的集合。无需任何实例化。

Math.constructor === Object(至少在 chrome 中是这样),所以您实际上是在扩展每个对象的原型(prototype),并且可能其他库正在枚举所有对象属性。例如:

Math.constructor.prototype.prop = 42;
k = {};
k.prop; // 42

关于javascript - 每个对象都应该有一个方法 'addEventListener' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699353/

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