"Construct" with variable arguments

  • Thread starter Michael Haufe (\TNO\)
  • Start date
T

Thomas 'PointedEars' Lahn

Dmitry said:
Function.prototype.construct = function (args) {

var
boundArgs = [].concat.apply([null], args),
boundFn = this.bind.apply(this, boundArgs);

Why must the thisArg for Function.prototype.bind() be `null'?
return new boundFn();

}

function Point(x, y) {
this.x = x;
this.y = y;
}

var point = Point.construct([2, 4]);


PointedEars
 
T

Thomas 'PointedEars' Lahn

Thomas said:
Dmitry said:
Function.prototype.construct = function (args) {

var
boundArgs = [].concat.apply([null], args),
boundFn = this.bind.apply(this, boundArgs);

Why must the thisArg for Function.prototype.bind() be `null'?
return new boundFn();

I think I understand now. The thisArg sets the [[BoundThis]] property but
that property is not used as there is a special [[Construct]] method
(15.3.4.5.2) for functions created with Function.prototype.bind()
(15.3.4.5). So you can use any value for the thisArg here, and they used
the most simple one.


PointedEars
 
A

Asen Bozhilov

Lasse said:
3. Create the Point object without using the Point constructor:
   function Point() {
     var self = this;
     if (!(self instanceof Point)) {
       self = new UninitializedPoint;
     }
     // initialize self
     self.x = arguments[0];
     self.y = arguments[1];
   }  
   function UninitializedPoint() {}
   UninitializedPoint.prototype = Point.prototype;

You have to explicitly return the `self' from the constructor,
especially when the `Point' it has called as a function, instead of
`new Point`.
Your approach does not solve the problem the variable length of
arguments, but it is really elegant and allows for implement it
without full emulation of internal [[Construct]].

Function.prototype.construct = (function () {
function F(constructor, args) {
constructor.apply(this, args);
}

return function (args) {
F.prototype = this.prototype;
return new F(this, args);
};
})();


//Soshnikov ES5 example

function Point(x, y) {
this.x = x;
this.y = y;
}

var foo = Point.construct([2, 3]);

print(foo.x);
print(foo.y);
print(foo.constructor);

This approach increase the call stack size, but I think it is the most
straightforward and compatibility way to achieve variable length of
passed arguments to certain constructor.

Regards.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
VinayKumar Nevatia
Top