javascript 一些函数的实现 Function.prototype.bind, Array.prototype.map

* Function.prototype.bind

Function.prototype.bind = function() {
var self = this,
context = [].shift.call(arguments),
args = [].slice.call(arguments);
return function() {
return self.apply(context, [].concat.call(args, [].slice.call(arguments)));
}
}

 // test

// test
var obj = {
name: 'mingzhanghui'
};
var func = function(a, b, c, d) {
console.log(this.name);
console.log([a,b,c,d]);
}.bind(obj, 1, 2); func(3,4);

  

* Array.prototype.map

Array.prototype.map = function(callback) {

	var T, A, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0; if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = arguments[1];
}
A = new Array(len);
k = 0; while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
};

  

上一篇:js 数组map用法 Array.prototype.map()


下一篇:JavaScipt30(第十八个案例)(主要知识点:Array.prototype.map)