javascript - Object.Prototype Methods and 'Use Strict' in an IIFE (Immediately-Invoked Function Expression) -
the original code:
'use strict'; function gitjs(config) { var defaults = { inheriting: false, clientid: undefined, accesstoken: undefined, baseurl: 'https://api.github.com', mode: 'read' }; this.config = $.extend(defaults, config); } /** * gets jquery method gitjs#generateapirequest going use send ajax request. * * @param {string} httpverb http verb request use, * @return string */ gitjs.prototype.getcommandmethod = function (httpverb) { var method = $.get; switch (httpverb) { case 'get': method = $.get; break; case 'post': method = $.post; break; } return method; }; ...
the new code:
(function() { 'use strict'; 'use strict'; function gitjs(config) { var defaults = { inheriting: false, clientid: undefined, accesstoken: undefined, baseurl: 'https://api.github.com', mode: 'read' }; this.config = $.extend(defaults, config); } /** * gets jquery method gitjs#generateapirequest going use send ajax request. * * @param {string} httpverb http verb request use, * @return string */ gitjs.prototype.getcommandmethod = function (httpverb) { var method = $.get; switch (httpverb) { case 'get': method = $.get; break; case 'post': method = $.post; break; } return method; }; ... }());
as code stands, when attempt:
var gitjs = new gitjs();
i told gitjs undefined
what hell thinking:
- i don't want put
use strict
inside of every method. - i want code play nice if gets minified , concatenated file.
- i want use
.prototype
syntax ease of inheritance later on (and code clarity) - i don't want make global
var gitjs
variable because overridden else's script. - i assume user invoke object constructor via
new
keyword
for record, know i'm wrong. way wrong. can't seem figure out flaw in thinking lies , i'd love guidance.
your problem gitjs private variable of invoked function. can't hide function in private scope , make publicly available @ same time. mutually exclusive goals.
therefore, want either explicitely set global variable, via window
var gitjs; (function() { 'use strict'; gitjs = function(){ ... } ... }());
or return exported function inside iife.
var exportedgitjs = (function(){ //using different name clear... 'use strict'; var gitjs = function(){ ... } ... return gitjs; }());
ok, lied. can make javascript modules without having rely on global variables usualy means using different module-creation convention and/or using module library. highly recommend check out http://requirejs.org/ if interested in this.
Comments
Post a Comment