<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>this之软绑定</title>
</head>
<body>
<script type="text/javascript">
// 软绑定
if (!Function.prototype.softBind) {
Function.prototype.softBind = function(obj) {
var fn = this;
// 捕获所有 curried 参数
var curried = [].slice.call( arguments, 1 );
var bound = function() {
return fn.apply(
(!this || this === (window || global)) ? obj : this,
curried.concat.apply( curried, arguments )
);
};
bound.prototype = Object.create( fn.prototype );
return bound;
};
}
var name1 = { name: 'agugua' };
var name2 = { name: 'LiMing' };
function showName(){
console.log('My name is ' + this.name)
}
//未软绑定
name2.showName = showName;
name2.showName(); // My name is LiMing"
//软绑定
name2.showName = showName.softBind(name1);
setTimeout(name2.showName, 60); // My name is agugua
</script>
</body>
</html>
javaScript中关于this之软绑定应用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。