Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery data()与对象(性能)_Javascript_Jquery_Performance - Fatal编程技术网

Javascript jQuery data()与对象(性能)

Javascript jQuery data()与对象(性能),javascript,jquery,performance,Javascript,Jquery,Performance,我想知道使用jQuery数据为对象绑定数据或使用这种对象,哪种方法更有效。我正在尝试为我的应用程序创建某种模型。这是目标代码 var PersonData = function () { var that = {}, _name = 0, _age = 0.0, _domId = false; that.data = initData(); //This is for initing data from options

我想知道使用jQuery数据为对象绑定数据或使用这种对象,哪种方法更有效。我正在尝试为我的应用程序创建某种模型。这是目标代码

var PersonData = function () {
    var that = {},
        _name = 0,
        _age = 0.0,
        _domId = false;

    that.data = initData();

    //This is for initing data from options
    function initOptions () {
        return {
            name: _name,
            age: _age,
            domId: _domId
        }
    }

    that.setName = function (name) {
        that.data.name = name;
    }

    that.getName = function () {
        that.data.name;
    }

    // I forgot to add dom id, now there is id for binding
    that.setDomElementId = function (id) {
        that.data.domId = id;
    }

    //Add getters and setter

    return that;
}
谢谢你的意见

顺便说一句,在textmate for javascript中有生成getter和setter的好插件吗?jQuery的
。data()
用于将数据附加到DOM元素。如果没有触摸DOM,则不要触摸
.data()


另外,我认为在JavaScript中不值得使用这种封装(除非您需要它来检测数据读/写)特别是如果您关心性能,直接访问对象的属性是一个更好的选择。JavaScript是一种动态语言,接受它:)

+1接受语言的属性。如果可以的话,我会给另一个+1,用于将数据与表示(DOM)分离。该死,我忘了为对象添加DOM id,对此我很抱歉。感谢您提供的封装提示。@用户,这取决于您希望如何访问对象。如果您将它们保存在某个JS数组/对象中,那么请坚持使用您所拥有的。如果您想在给定jQuery选择器的情况下访问它们。。。然后使用jQuery的
.data()
。但就性能而言,直接属性访问比函数调用快。请为另一个问题保留“顺便提一下”问题。具有默认属性的数据结构的习惯用法是:
function PersonData(name,age){this.name=name | |”“;this.age=age | | | 0}
,但是,像这样错误的默认值,我只会让它们不被定义。