javascript - Why does jQuery use "new jQuery.fn.init()" for creating jQuery object but I can't? -
I try to create some class based jQuery styles like the following code.
MyClass = window.myClass = function (x, y) {new myclass.fn.init (x, y); }; MyClass.fn = myClass.prototype = {init: function (x, y) {// logic to create myClass object. }};
I do not understand why jQuery is the new keyword for creating its own class because, by my use, javascript always creates myClass.init object instead of myClass object. However, I try to delete the new keywords in myClass Constructor. But it's still not a change Can you tell me why jQuery can do this, but can not I give some code to use in the init function or not?
Anyway, I can use the following code instead of the jQuery code to make it the object. What is different between my code & amp; JQuery code? What is the advantage of using jQuery style?
myClass = window.myClass = function (x, y) {this.init (x, y); }; MyClass.fn = myClass.prototype = {init: function (x, y) {this.x = x; this. Y = y; }}; PS I like the code to write, which separates the initial argument into the function because it is very easy for others to override this function such that my code is used to enter my code It is like. // myclass myClass's override init function Fn._old_init = myClass.fn.init; MyClass.fn.init = function () {// Init, this argument to something before ._old_init (); Logic for something after // init;);
Thanks,
The approach should work perfectly. One thing that you may be missing is with the fact that, using this technique, you are not making an example of myClass
; You are making an example of myClass.prototype.init
.
Therefore, there will be no way defined in myClass.prototype
for example. You want to make sure the prototype of init
prototype number of myClass
:
myClass.fn.init. Prototype = myClass.fn;
FWI, I do not see any real benefit in this approach, what's wrong with this? -
function myClass (x, y) {if (! (This example myClass)) Return to the new myClass (x, y); } // Create Example} myClass.prototype = {/ * Methods} // It can still be written: var oldMyClass = myClass; Do the MyClass function (x, y) {// Here are some stuff ... Return new old Mai class (X, Y); }
Comments
Post a Comment