read the _.bind in source code, I didn't understand when the statement this instanceof bound will be true. Could anyone give an example.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
For starters, Function.prototype.bind won't be defined. If bound is used as a constructor, (this instanceof bound) will be true. For example:
Function.prototype.bind = null;
var Constructor = function () {};
var BoundConstructor = _.bind(Constructor, {});
var b = new BoundConstructor(); // (this instanceof bound) === true
You can use the debugger to trace through this fiddle.
Related
I found this piece of code used in a dependency injection implementation in javascript:
resolve: function() {
var func, deps, scope, args = [], self = this;
func = arguments[0];
deps = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].replace(/ /g, '').split(',');
scope = arguments[1] || {};
return function() {
var a = Array.prototype.slice.call(arguments, 0);
for(var i=0; i<deps.length; i++) {
var d = deps[i];
args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
}
func.apply(scope || {}, args);
}
}
And I was wondering myself why that ugly func = arguments[0] was there, because I'd write that with just: function(func) { ... }... is there any difference?
There is a difference:
function a(arg) { return arg; };
function b() { return arguments[0]; };
console.log(a.length); // 1
console.log(b.length); // 0
But I think it more to be compatible with arguments[1] || {} which is necessary to use the default value.
How do I splat across objects without using ECMA6 features?
Attempt
function can(arg0, arg1) {
return arg0 + arg1;
}
function foo(bar, haz) {
this.bar = bar;
this.haz = haz;
}
myArgs = [1,2];
With can I can just do:
can.apply(this, myArgs);
When trying with foo:
new foo.apply(this, myArgs);
I get this error (because I'm calling new):
TypeError: function apply() { [native code] } is not a constructor
Using Object.create
function foo(bar, haz) {
this.bar = bar;
this.haz = haz;
}
x = Object.create(foo.prototype);
myArgs = [5,6];
foo.apply(x, myArgs);
console.log(x.bar);
Using Object.create(proto) is the right way to go about this.
Coco and LiveScript (Coffeescript subsets) offer a workaround:
new foo ...args
compiles to
(function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args), t;
return (t = typeof result) == "object" || t == "function" ? result || child : child;
})
(foo, args, function(){});
And in CoffeeScript:
(function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(foo, args, function(){});
These hacks are ugly, slow, and imperfect; for example, Date relies on its internal [[PrimitiveValue]]. See here.
Considering MDN's Object.create polyfill:
if (typeof Object.create != 'function') {
(function () {
var F = function () {};
Object.create = function (o) {
if (arguments.length > 1) { throw Error('Second argument not supported');}
if (o === null) { throw Error('Cannot set a null [[Prototype]]');}
if (typeof o != 'object') { throw TypeError('Argument must be an object');}
F.prototype = o;
return new F();
};
})();
}
Focusing particularly on these two lines:
F.prototype = o;
return new F();
I was wondering, why isn't it appropriate to set F.prototype.constructor = F;?
F.prototype = o;
F.prototype.constructor = F; // why not?
return new F();
I was wondering, why isn't it appropriate to set F.prototype.constructor = F;?
F is a temporary function, and it seems intentional that there is no way to reference it from outside Object.create.
I am working on the curring function and partial application,
I am trying to improve the function schonfinkelize:
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
This function permit to pass as argument a function and a part of the argument of the function passed as argument (partial application) so the first time you return a function and then when you fire the function again the result.
function add(x, y, z){
return x + y + z;
}
var val = schonfinkelize(add, 1, 2);
console.log( val(3) ) // console output--> 6
I want check inside schonfinkelize the number of arguments need to the function "add" (but it should work with every function) so I can choose when return another function or directly the result of the function "add".
bacause if I use schonfinkelize in this way:
var val2 = schonfinkelize(add, 1, 2, 3);
console.log( val2 ) // --> function
console.log( val2() ) // --> 6
I have to fire the function two time, instead a want avoid this behavior and define directly the value if the arguments are sufficient.
A possible solution could be the following:
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
//* I have added this ********
if(fn.apply(null, stored_args))
return fn.apply(null, stored_args);
//****************************
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
Could be because it returns immediately the result if the fn.apply(null, stored_args) return something that is not "null" or "NaN" but I think is not really performant and then I want work with the arguments.
As long as you put in place a requirement that the parameters defined for the function passed reflect the actually number of arguments that are to be ultimately received, you can use the .length property of the function to do the comparison of passed arguments to anticipated arguments.
function schonfinkelize(fn) {
if (fn.length === arguments.length - 1)
return fn.apply(this, [].slice.call(arguments, 1));
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
return function(){
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
}
}
Side note... you can avoid the .slice() if you cache the fn in a new variable, and overwrite the first argument with the this value, then use .call.apply()...
if (fn.length === arguments.length - 1) {
var func = fn;
arguments[0] = this;
return func.call.apply(func, arguments);
}
In strict mode browsers you could even avoid having the make the new variable since the parameters are no longer mapped to changes in the arguments. But this doesn't work in browsers that don't support strict mode.
I don't think there is a correct way to determine number of arguments for arbitrary function. I prefer to store len in function if it is necessary, and check if it is defined, and if it is and if fn.len == stored_args.length then return function that just returns value.
function schonfinkelize(fn){
var
slice = Array.prototype.slice,
stored_args = slice.call(arguments, 1);
if (fn.len != undefined && fn.len == stored_args.length) {
var val = fn.apply(null, stored_args);
return function () {
return val;
};
}
return function () {
var
new_args = slice.call(arguments),
args = stored_args.concat(new_args);
return fn.apply(null, args);
};
}
var f = function (a, b, c) {
return a + b + c;
};
f.len = 3;
var g = schonfinkelize(f, 1, 2);
alert(g); // function () { var new_args = slice.call(arguments), args = stored_args.concat(new_args); return fn.apply(null, args); };
alert(g(3)); // 6
var g = schonfinkelize(f, 1, 2, 3);
alert(g); // function () { return val; };
alert(g()); // 6
I want propose also a personal evolution of the code but I have to said thanks to squint to has resolved the problem, simply suggest me to use the property .length.
The next level it is in my opinion permit to create a partial function able to be called every time you want until you finish to fill all the arguments, I have also simplified the code:
function schonfinkelize(fn, stored_args){
if(fn.length == stored_args.length)
return fn.apply(null, stored_args);
return function(){
var
new_args = arguments[0],
args = stored_args.concat(new_args);
if(fn.length == args.length)
return fn.apply(null, args);
return schonfinkelize(fn, args);
}
}
function add(x, y, w, z){
return x + y + w + z;
}
var
val = schonfinkelize(add, [1, 2, 3, 4]),
val2 = schonfinkelize(add, [1, 2]),
val3 = schonfinkelize(add, [1]);
// checking
console.log(val); // output --> 10 // called only 1 time
console.log(val2([3, 4])); // output --> 10 // called in 2 times
val3 = val3([2]);
val3 = val3([3]);
console.log(val3([4])); // output --> 10 // called 4 times!
I have a class definition method for create class in javascript:
var Class = function() {
var clazz = null,
pros = {};
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (typeof arg == "function") arg = arg.prototype;
else {
arg.init && (clazz = arg.init, delete arg.init)
}
for (var p in arg) pros[p] = arg[p];
}
clazz.prototype = pros;
return clazz;
};
var Person = Class({
init: function(name) {
this.name = name;
},
say:function(){
console.info(this.name);
}
});
var Man = Class(Person, {
init: function(name) {
Person.apply(this, arguments);
this.gender = 'man'
}
});
var m = new Man('kk');
console.info(m instanceof Man);
console.info(m instanceof Person);
However, it does not support the instanceof operator.
Any idea to fix it?
You should keep track of the prototype chain to make instanceof work. What you're currently doing is merely copying properties into one object, and use that as prototype of the returned function. As a result, the information that Parent is a parent of Man is lost.
You'd need to set the prototype instead of copying. Since you need to modify an existing object to set the underlying prototype of, the deprecated __proto__ property is required. Object.create cannot be used here, because that returns a new object.
Edit: It is possible without __proto__, but you'd need the function F trick: http://jsfiddle.net/p9pvQ/.
var clazz = null,
pros = Object.prototype; // root of chain
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (typeof arg === "function") {
arg = arg.prototype;
} else {
if(arg.init) {
clazz = arg.init;
delete arg.init;
}
var o = arg;
arg = (function() { function F() {}; F.prototype = pros; return new F; })();
for(var key in o) arg[key] = o[key];
}
pros = arg;
}
m will then have the prototype chain as follows:
Class.init // m
gender: "man"
name: "kk"
__proto__: F // Man
__proto__: F // Person
say: function (){
__proto__: Object // Object.prototype
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
... (Object.prototype functions)