一、bind的使用
1、bind初步使用及功能了解
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var a=1;
var o={
a:2
}
function hello(x,y,z){
console.log(this.a,x,y,z);
}
var world=hello.bind(o,'q');
var helloWorld=hello.bind();
world('w','e');
helloWorld();
总结:
函数调用bind方法
</script>
</body>
</html>
2、使用call和apply仿写bind方法函数newBind
// 使用call和apply重写bind方法
Function.prototype.newBind=function(target){
debugger;
var self=this;
var args=[].slice.call(arguments,1);//从下标为1的位置开始截取并返回一个新的数组
var temp=function(){};
var f=function(){
var _arg=[].slice.call(arguments,0);//把参数类数组转为数组并返回
return self.apply(this instanceof temp? this:(target || window),args.concat(_arg));
}
temp.prototype=self.prototype;
f.prototype=new temp();
return f;
}
function show(x,y,z,w){
console.log(this,x,y,z,w);
}
var Duyio={
x:20
}
var newShow=show.newBind(Duyio,1,2,3);
newShow(4);
二、instanceof的使用
用法介绍:判断左边元素是不是在右边元素的原型链上,是及返回true,否则返回false
function Foo(){};//构造函数Foo
var f1=new Foo();//构造函数实例f1;
console.log(f1 instanceof Foo) //true
//即说明:
f1.__proto__===Foo.ptototype;//实例的隐式原型等同于构造函数的显示原型
instanceof 方法内视
function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
var O = R.prototype;// 取 R 的显示原型
L = L.__proto__;// 取 L 的隐式原型
while (true) {
if (L === null)
return false;
if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true
return true;
L = L.__proto__;
}
}
js原型链图: