【问题标题】:Define dot functions like jQuery's ".map()", ".each()", etc定义点函数,如 jQuery 的“.map()”、“.each()”等
【发布时间】:2021-09-20 05:49:00
【问题描述】:

我有 2 个函数和一个这样定义的构造函数:

let mx = function(arr) {
    return new mx.fn.init(arr) 
}

mx.fn = mx.prototype = {
    constructor: mx,
}

init = mx.fn.init = function(arr) {
    //do things and return an object containing data about arr
}

所以这段代码运行良好,调用mx(array) 会返回想要的对象。 现在,我如何定义函数来操作这个对象?我想定义诸如mx(array).addRow(row) 之类的函数来更改mx(array) 返回的对象中的数据,但无法做到这一点。 我试图在mx.fn 中定义它,如下所示: addRow: function(arr) { //do smth } 但它不起作用。 我也尝试过mx.prototype.addRow = function(row) { //do smth }。 你知道这是否可能吗?它看起来很像 jQuery 的 $('#id').css('color': 'red'),但我不确定这是否同样有效。 我对很多这些概念都很陌生,所以我对所有这些原型有点迷失......

提前感谢您的帮助!

【问题讨论】:

    标签: javascript jquery constructor javascript-objects prototype


    【解决方案1】:

    需要设置init函数的prototype

    let mx = function(arr) {
        return new mx.fn.init(arr) 
    }
    let init = function(arr) {
        //do things and return an object containing data about arr
    }
    mx.fn = init.prototype = {
        addRow(row){
            // do something
        },
        init: init
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 2010-10-12
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 2012-07-22
      • 2012-09-10
      相关资源
      最近更新 更多