开发者

Using a constructor on a JavaScript static instance

开发者 https://www.devze.com 2023-04-08 23:14 出处:网络
I\'m writing a JavaScript library in which I want some methods and properties public and other private. The following seems a great way of doing this whilst wrapping everything up into a single object

I'm writing a JavaScript library in which I want some methods and properties public and other private. The following seems a great way of doing this whilst wrapping everything up into a single object.

(function (window) {
   var Thing = function() {
      // private var
      var variable = "value";

      return {
         // public method
         me开发者_StackOverflowthod:function() {
            alert(variable);
         }
      }
   }();

   window.Thing = Thing;

})(window);

Thing.method();

Which is great. (Mostly grabbed from here).

However, I'd still like to be able to use the constructor of Thing to pass in some arguments.

Is there anyway I can provide a constructor in the return statement, or use prototype to override the constructor? So I can call:

Thing(stuff);

Right now, if I try that it causes:

Uncaught TypeError: Property 'Thing' of object [object DOMWindow] is not a function

Which makes sense as it's not returning itself, but ideally it'd be possible to call a constructor.

OR, is this just baaaad and I should steer clear of some or all of this?


To accomplish what you are asking, do something like this:

(function (window) {
   var thingMaker= function(stuff) {
      // private var
      var variable = "value";

      return {
         // public method
         method:function() {
            alert(variable);
         }
         alertStuff:function() {
            alert(stuff);
         }
      }
   };

   window.thingMaker= thingMaker;

})(window);

var myThing = window.thingMaker(stuff);
myThing.alertStuff()

More information can be found by searching the googlenets for Douglas Crockford. Some great and very informative videos by him are available on yui theater. But I would have to ask, why create another framework when there are already so many great ones out there (jquery,prototype,yui,dojo to name a few)


Thing is already created, so you are always going to be too late to call a 'constructor'.

You could pass variables in like this:

(function (window, var1, var2) {
  var Thing = function() {
  // private var
  var variable = "value";

  return {
     // public method
     method:function() {
        alert(variable);
     }
  }
}();
window.Thing = Thing;
})(window, var1, var2);


Thing is an Object with one method called method:

  {
     // public method
     method:function() {
        alert(variable);
     }
  }

Thing.method(); // alerts "value"

You could return instead:

function () {
    alert(arguments)
}

Then

Thing(6,5,4); // alerts 6,5,4
0

精彩评论

暂无评论...
验证码 换一张
取 消