在javascript中访问扩展对象

时间:2013-02-11 18:03:30

标签: javascript jquery object instantiation

我在创建有用的实例时遇到了一些麻烦 从另一个JS文件,我想改变的属性 实例并使用方法。如果不是这样的话,无论你建议什么 可能。这扩展了,这个结构令我困惑。

(function($) {

$.extend({
    usefulThings: new function() {
        this.defaults = {
            prop_path:'/la/lala',
            //OTHER STUFF
        };
        this.construct = function(options) {
            return this.each(function() {
                var setting;
                this.settings = {};
                settings = $.extend(this.settings, $.usefulThings.defaults, options);
                $this = $(this);

                //OTHER STUFF
                $.data(this, "usefulThings",settings);
                // FIRST METHOD CALL
                //OTHER STUFF
            });
        };
        //SOME METHODS
    }
});
$.fn.extend({
    usefulThings: $.usefulThings.construct
}); 
})(jQuery);      

我见过有用的话从脚本块调用,如:

$("#myDivName").usefulThings({
  prop_path: '/la/lala' //these seems to get overwritten in the above
});

1 个答案:

答案 0 :(得分:0)

首先,看看MDN's introduction to the this keyword。在.each的jQuery文档中。

接下来,查看how does jquery chaining work?以了解构造方法。

然后,您应该注意到在这种情况下使用new关键字是绝对不合适的。表达式应该用简单的对象文字替换:

{
    defaults: {
        prop_path:'/la/lala',
        // …
    },
    construct: function(options) {
        …
    },
    //SOME METHODS
}

现在,jQuery.extend。来自文档的相关句子是

  

如果只向$.extend()提供了一个参数,则表示省略了target参数。在这种情况下,假定jQuery对象本身是目标。通过这样做,您可以向jQuery命名空间添加新功能。这对于希望向JQuery添加新方法的插件作者非常有用。

$.fn.extend(实际上是=== $.extend)也是如此,它扩展了jQuery.fn对象,这是jQuery原型对象的快捷方式。