jquery - Variable as a function at the same time in JavaScript -
i want implement this.
myvar.myanothervar; myvar.mymethod(); myvar("sample text");
and how jquery implemented it
jquery.fn; jquery.ajax(); jquery("#mybtn");
how can implement jquery holds on single namespace? prototype? how can variable can used invoke function @ same time?
thank :)
functions in javascript objects, can arbitrarily add properties them other object:
function foo() { // code when call `foo` goes here } foo.somedata = "bar"; foo.somefunction = function() { // code when call `foo.somefunction` goes here };
what jquery more complicated, , bit unusual, in couple of ways:
the
jquery
function (usually aliased$
) wrapper around call constructor function creates new object. (the constructor function calledinit
.)they've added reference
init
function'sprototype
property in property onjquery
function calledfn
. both properties (jquery.fn
,init.prototype
) refer object become instance's prototype when usenew init
.they've also referred same object
jquery.prototype
, thoughjquery
isn't used constructor function.$() instanceof $
true
.
but don't have things you've described. can, of course, don't have to.
if want 2 things, basic structure looks this:
var foo = function() { // public function function foo(args, here) { return new init(args, here); } // hidden constructor function function init(args, here) { // ...do `this`, perhaps } // object becomes prototype of instances created via `new init` foo.fn = foo.prototype = init.prototype = { // instance-specific function, jquery's `css` instancemethod: function() { // has access `this` } }; // random piece of "static" (not instance-specific) data foo.somedata = "bar"; // "static" (not instance-specific) function, jquery's `$.ajax` foo.staticmethod = function() { // doesn't have (useful) access `this` }; return foo; }();
Comments
Post a Comment