Skip to content

Instantly share code, notes, and snippets.

@zhenyong
Last active December 19, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhenyong/5906816 to your computer and use it in GitHub Desktop.
Save zhenyong/5906816 to your computer and use it in GitHub Desktop.
###line:80 数字字符串转成数字的方便方式
//in chrome
+'0.123'//0.123
+'0.123e4'//1230
+void 0//NaN
+null//0
+false//0
+true//1
+NaN//NaN
###line:80 判断一个变量是不是数字的hack
var a = '1';
a === +a//false
var arr = ['1'];
arr[0] === +arr[0];//false
var b = 1;
b === +b;//true
###line:143 JavaScript会提升变量声明。这意味着 var 表达式和 function 声明都将会被提升到当前作用域的顶部(无论var是否在代码块里面)
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
...
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
//起初怀疑这里的keys是否没有被声明
index = keys ? keys[--length] : --length;
...
});
};
相当于
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
...
var length = obj.length;
var keys;//提升到作用域顶部
if (length !== +length) {
keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
...
});
};
###line:616 bind的实现要防止对构造函数做保护,当对一个构造函数使用bind,再调用的时候this是参数中的context,这时候有的初始化就不正常
//源代码:
var ctor = function() {};
_.bind = function(func, context) {
var args, bound;
...
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;
};
};
//假设代码变成这样
_.bind = function(func, context) {
var args, bound;
...
args = slice.call(arguments, 2);
return bound = function() {
//这里为什么要做这个判断呢
//if (!(this instanceof bound))
return func.apply(context, args.concat(slice.call(arguments)));
};
};
//案例代码
function Person(name) {
this.name = name;
}
var obj={name:'obj'}
Person = _.bind(Person, obj);
var p = new Person('the name');
console.info(p.name);//==> undefined
console.info(obj.name);//==> 'the name'
//因为_.bind(Person, obj)之后,Person构造函数里面的this就是obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment