Javascript如何绑定当前的作用域

说白了就是怎么把当前的this指针传递到内部嵌套的其它函数当中,总的来说,有两种方法。

绑定方法一: 

参考这面这篇文章(JS常用代码片段集合), 里面有介绍一种绑定函数的this指针的方法,具体用法大致如下。

function bind(func, obj)  
{  
    return function(){  
        func.apply(obj, arguments);  
    };  
}  

function test()
{
	this.abc = "default";

	var func = function(){
		console.log(this.abc);
	};

	bind(func, this)();
}

var a = new test();

绑定方法二: 

function test()
{
	this.abc = "default";

	var func = (function(_this) {
		return function() {
			console.log(_this.abc);
		};
	})(this);

	func();
}

var a = new test();

 

 



文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 4622