一 函数系列
1、实现call、实现apply 、实现bind
function sayName1(){
name='gg'
money='1'
console.log("我是"+this.name)}
let students2 ={
name='caomei'
money='10'
sayName2(){ console.log("我是"+this.name)}
}
let students3 ={
name='caomei'
money='100'
sayName3(Age,sex){ console.log("我是"+this.name+年龄+Age+性别+sex)}
}
let students4={
name='timi'
money='1000'
}
sayName1.call(obj1)
students2.sayName2.call(obj1,23,'男')
students3.sayName3.call(obj1,23,'男') 会直接调用。
student3.sayName3.apply(obj1,[23,'男']) 会直接调用。
let save_fn =Students.sayName3.bind(obj1,23,'男') save_fn()。不会直接调用,可以多次调用。
function myfunc1(){
this.name = 'Lee';
this.myTxt = function(txt) {
console.log( 'i am',txt );
}
}
function myfunc2(){
myfunc1.call(this);
}
var myfunc3 = new myfunc2();
myfunc3.myTxt('Geing'); // i am Geing
console.log (myfunc3.name); // Lee
知识点1: this是动态的。谁调用函数,this指向谁。
解析1:sayName1 和sayName2都是函数都可以调用里面的方法。但我想让其他对象obj1也调用里面的方法。 虽然obj1是写在括号里面的,可以这么解读。 1、sayName1函数改变了this的指向。 2、或者是obj1对象调用了sayName方法。
解析2:call、apply,bind
实现call :