javascript - 如何在 Javascript 中修改 Array.prototype

标签 javascript

我正在尝试使用一种方法修改 Javascripts 数组类型,该方法仅在数组不存在时才将值推送到数组。

这是我的代码:

// add a method conditionally
Array.prototype.method = function (name, func){
    if(!this.prototype[name]){
        this.prototype[name] = func;
        return this;
    }
};

// exclusive push
Array.method('xadd', function(value){
    if(this.indexOf(value) === -1){
        this.push(value)
    };
    return this;
});

但是,当我运行代码时,Firefox 中的暂存器返回:

/*
Exception: TypeError: Array.method is not a function
@Scratchpad/3:19:1
*/

我想要一个普通的方式来做到这一点。不是库,因为我正在编写一个开源库。

最佳答案

当您在 Array.prototype 上放置一个方法时,该方法将在 Array 的实例上可用。

// Add the custom method
Array.prototype.method = function() {
    console.log('XXX');
}

var foo = [];
// prints XXX
foo.method();

关于javascript - 如何在 Javascript 中修改 Array.prototype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957706/

相关文章:

javascript - 文本在对话框中排成一行

javascript - CSS3 : Is it possible to fire a transition on an element when the page is scrolled down the first viewport?

javascript - 我的 Ajax PHP 代码无法正常工作

javascript - 无法覆盖对象/类上的 toString

javascript - 检测 ES6 类中的静态超方法

php - https 安全 cookie 是否可以防止 XSS 攻击?

javascript - 如何将计算的可观察对象添加到 knockoutjs 映射

javascript - express + hogan 如何处理session?

javascript - odoo10中如何将一个模块中的JS文件继承到另一个模块中的另一个JS文件

javascript - Contenteditable div 输入问题(keyCode 13)