javaScript中关于this之软绑定应用
作者:
阿古瓜 | 来源:发表于
2018-10-22 12:10 被阅读0次<!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之软绑定应用
本文链接:https://www.haomeiwen.com/subject/tsawzftx.html
网友评论