javascript - How to not use the `new` operator in JS API? -
so came across this article mr. baranovskiy says people shouldn't have use new
operator use api. have created this basic example lets create instances of colorbox
line of code var box = new colorbox(node, options);
how implement have in example without using new
operator?
js:
var colorbox = function(node, options) { this.setsize = function(){ node.style.width = options.width + 'px'; node.style.height = options.height + 'px'; } this.setcolor = function(color){ node.style.backgroundcolor = color || options.color; } this.setsize(); this.setcolor(); } var node = document.getelementbyid('thing1'); var options = { color: 'red', width: 200, height: 200 } var box = new colorbox(node, options); settimeout(function(){ box.setcolor('blue'); }, 2000);
first, don't agree article - think new
reasonable way of writing code, , makes clear you're creating instance of "class", object-oriented language.
but...
take @ second approach on this answer, shows how have function return new instance if caller leaves off new
(if this
not instance of "class", caller left off new
, , this
global window). that's 1 way of not requiring user type new
, while still safely returning new instance each time.
var colorbox = function(node, options) { if (!(this instanceof colorbox)) return new colorbox(node, options); // rest of constructor stuff };
Comments
Post a Comment