1,认识js中bind的方法
//复制了一份的时候,把参数传入到了f1函数中,x===>10,y===>20,null就是this,默认就是window
//bind方法是复制的意思,参数可以在复制的时候传进去,也可以在复制之后调用的时候传入进去
//apply和call是调用的时候改变this指向
//bind方法,是赋值一份的时候,改变了this的指向
function f1(x,y){
console.log((x+y)+":=====>"+this.age);
}
var ff=f1.bind(null);
ff(10,29);
//让person调用这个
function Person() {
this.age = 1000;
}
var p=new Person();
var ff=f1.bind(p,10,20);
ff();
console.log("==========================");
function Person(age) {
this.age=age;
}
Person.prototype.play=function () {
console.log(this+"====>"+this.age);
};
function Student(age) {
this.age=age;
console.log(age);
}
var per=new Person(10);
var stu=new Student(20);
//复制了一份,执行的是stu中的方法
var ff=per.play.bind(stu);
ff();
//bind是用来复制一份
//使用的语法:
/*
* 函数名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个函数
* 方法名字.bind(对象,参数1,参数2,...);---->返回值是复制之后的这个方法
*/
2.bind使用的小案例
//通过对象,调用方法,产生随机数
function ShowRandom() {
//1-10的随机数
this.number=parseInt(Math.random()*10+1);
}
//添加原型方法
ShowRandom.prototype.show1=function () {
//改变了定时器中的this的指向了,本来应该是window,现在是实例对象了
window.setInterval(this.show2.bind(this),1000);
};
//添加原型方法
ShowRandom.prototype.show2=function () {
//显示随机数--
console.log(this.number);
};
//实例对象
var sr=new ShowRandom();
//调用方法,输出随机数字
//调用这个方法一次,可以不停的产生随机数字
sr.show1();
3.函数中的成员
//函数中有一个name属性----->函数的名字,name属性是只读的,不能修改
//函数中有一个arguments属性--->实参的个数
//函数中有一个length属性---->函数定义的时候形参的个数
//函数中有一个caller属性---->调用(f1函数在f2函数中调用的,所以,此时调用者就是f2)
function f1(x,y) {
console.log(f1.name);
console.log(f1.arguments.length);
console.log(f1.length);
console.log(f1.caller);//调用者
}
// f1.name="f5";
// f1(10,20,30,40);
// console.dir(f1);
function f2() {
console.log("f2函数的代码");
f1(1,2);
}
f2();