简体   繁体   English

实例化

[英]jQuery etc. Instantiation

OOP usually requires instantiation (creating an instance of class before using) like this: OOP通常需要实例化(在使用之前创建类的实例),如下所示:

var x = new String();

In jQuery (and other frameworks) we can use object without instantiation, eg(no 'new'): 在jQuery(和其他框架)中,我们可以使用没有实例化的对象,例如(没有'new'):

$('#myid').click(function(){
//code
});

Here's my question: how do framework authors make it?? 这是我的问题:框架作者如何制作它? How to make framework ready for use without 'new' instantiation?? 如何在没有“新”实例化的情况下使框架可以使用?

Thanks in advance!! 提前致谢!!

The simplest, hand-waviest answer (that leaves out a lot about how JavaScript is different from class-based languages) is that a new object is created and returned from the jQuery function. 最简单,最有用的答案(遗漏了很多关于JavaScript与基于类的语言的不同之处) 创建一个新对象并从jQuery函数返回。

One of the first things you'll see in the jQuery source: 您将在jQuery源代码中看到的第一件事:

var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
}

You can see that $ is simply an alias for jQuery later in the source: 您可以在以后的源代码中看到$只是jQuery的别名:

// Expose jQuery to the global object
return (window.jQuery = window.$ = jQuery);

javascript is a prototype based language , there is no inheritance - all behavior is achieved by cloning objects and/or attaching new fields to existing objects. javascript是一种基于原型的语言 ,没有继承 - 所有行为都是通过克隆对象和/或将新字段附加到现有对象来实现的。

In the example you have given 在你给出的例子中

$('#myid').click(function(){
//code
});

you are actually passing an anonymous function to the click function which is defined as an inner function on an object defined by the jQuery library - which is created via the global parametrized $ function (which internally uses new as pointed out by @lwburk in his answer). 你实际上是将一个匿名函数传递给click函数, click函数被定义为jQuery库定义的对象的内部函数 - 它是通过全局参数化$函数创建的(内部使用new如@lwburk在其答案中所指出的那样) )。 Functions are first class citizens in javascript - they can be used directly, or as part of an object, which then makes them appear as if they were methods within the outer object: 函数是javascript中的一等公民 - 它们可以直接使用,也可以作为对象的一部分使用,然后使它们看起来好像是外部对象中的方法:

 [object returned by function]
 $            ('#myid')       .click(          function() {} );
 ^             ^               ^
 function      parameters      inner function  ^ parameter of type function

You can make a method that is wrapped with a self-evoking function. 您可以创建一个包含自我唤起功能的方法。

(function() {
    var iAm = window.iAm || {};

    iAm = {
        Awesome: function()
        {
            alert('Yea you are!');
        },

        Lame: function()
        {
            alert('aww man.');
        }
    };

    window.iAm = iAm;

})();

iAm.Awesome(); // will alert "Yea you are!"
iAm.Lame(); // will alert "aww man."

JavaScript is a dynamic, scripting, prototype-based language. JavaScript是一种动态的,脚本化的,基于原型的语言。 The instantiation and memory management comes from the interpreter. 实例化和内存管理来自解释器。

Because JS is prototypal, functional and class-less, the new keyword is a bit different from other languages. 因为JS是原型的,功能性的和无类的,所以new关键字与其他语言略有不同。

The difference between 和...之间的不同

var D = new Dog();

and

var D = Dog();

is that using the new keyword will return the object for which it is invoking. 是使用new关键字将返回它正在调用的对象。

Consider this: 考虑一下:

function Dog() {

  // a property
  this.breed = "chocolate lab";

  // a method
  this.bark = function(){
    alert("woof");
  }
}

Then you can call methods and pull properties from the object. 然后,您可以调用方法并从对象中提取属性。

var D = new Dog();

    D.breed; // [string] 'chocolate lab'
    D.bark(); // alerts "woof"

According to the Crockford school, to embrace the true prototypical nature of JavaScript you have to abolish pseudo-classical elements such as the new operator or the .prototype reference. 根据Crockford学校的说法,为了拥抱JavaScript的真正原型性质,你必须废除伪经典元素,例如new运算符或.prototype引用。

While lwburk is right in that in jQuery, $() is just a wrapper, you can actually 'instantiate' an object without new . 虽然lwburk在jQuery中是正确的,但$()只是一个包装器,你实际上可以在没有new情况下“实例化”一个对象。

var myClass = function () {
  var privateVar,

  instance = {
    member: 'foo',
    method: function () {
      privateVar = 'bar';
    }
  };

  return instance;
};

var newInstance = myClass();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery onchange等未检测到何时使用jQuery更改了输入 - Jquery onchange etc. doesnt detect when input changed with jquery jQuery:在dblclick上触发事件不起作用(但在keyup等上起作用) - jQuery: Triggering event on dblclick not working (but working on keyup etc.) jQuery变量中有趣的html故障,其中包含&,/等字符? - Interesting html glitch in jquery variable with characters like &, /, etc.? 扩展javascript库(下划线,jQuery,主干等) - Extending javascript libraries (underscore, jquery, backbone etc.) 使用jQuery为简单的编辑器获取所选文本,替换它等 - Get selected text, replace it, etc. using jQuery for a simple editor 在 vue.js 中需要其他库(jquery 等) - require other library (jquery or etc.) in vue.js 默认禁用jQuery单击,on('click'等。注册右键单击 - Disable by default jQuery click, on('click', etc. registering right clicks YAHOO.lang的jQuery版本(isUndefined,isNull,isString等) - jQuery version of YAHOO.lang (isUndefined, isNull, isString etc.) 关于通过jQuery进行图像替换褪色等的思考 - Thoughts on image replacement fading etc. via jQuery 在每个模块中是否有更好的方法要求Backbone,jQuery,下划线等? - Is there a better way to require Backbone, jQuery, underscore, etc. in every module?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM