1. 程式人生 > 其它 >重寫bind()方法

重寫bind()方法

技術標籤:javascriptjs

Function.prototype.myBind = function(ctx){
	var ctx = ctx ? Object(ctx) : window,
			originFn = this,
			args = [].slice.call(arguments, 1), //從第二個引數開始獲取
			//原型傳遞中介函式
			_tempFn = function(){};
		
		var newFn = function(){
			//返回新函式的引數列表
			var newArgs = [].slice.call(arguments);
			//如果返回的新函式進行new, this -> newFn建構函式, 否則 this -> ctx
return originFn.apply(this instanceof newFn ? this : ctx, args.concat(newArgs)); } //使用聖盃模式,目的是函式之間不會共用同一個原型鏈 _tempFn.prototype = this.prototype; newFn.prototype = new _tempFn(); return newFn; } function test(){ console.log(this, arguments); } test.prototype.myLove = 'xiaohong'
; var t = test.myBind({ a: 'xiao', b: 'hong' }, 'zhangsan'); t('lisi'); var newFn = new t('wangwu'); console.log(newFn.myLove);

結果:
在這裡插入圖片描述