1. apply() 方法:
作用:改变方法中的this指针。
说明:
调用一个对象的一个方法,用另一个对象替换当前对象。例如 A.apply(B, arguments); 即 B 对象应用到 A 对象的方法。
参数:
B.apply(A, arguments);
A:用来替换的新对象。
arguments:数组。
代码:
function show(title){
alert(`${title} + this.name`);
// 当前 this.name 为 null
}
let lisi = {name:'李四'};
show.apply(lisi, ['呼啦啦']);
// 实现构造函数继承
'use strict';
function Request(){
this.get = function(params = {}){
let option = Object.keys(params).map(i => i+'='+params[i].join('&'));
return `获取数据 API:${this.url}?{option}`;
};
}
function Article(){
this.url = 'article/index';
Request.apply(this, []);
}
let hd = new Article();
console.log(hd.get({row:20}));
function Lesson(){
this.url = 'lesson/index';
Request.apply(this, []);
}
let js = new Lesson();
console.log(js.get({row:20}));2. call() 方法:
与 apply() 方法类似,只是第二个参数不是数组,可以传递多个参数。
参数:
A.call(B, a, b, c, ...);
代码:
<body>
<button message='卖小邪'>button</button>
<button message='换大花'>button</button>
</body>
<script>
function show(){
alert(this.getAttribute('message'));
}
let bts = document.getElementsByTagName('button');
for (let i = 0; i < bts.length; i++){
bts[i].addEventListener('click', () => show.call(bts[i]));
}
</script>
function show(title){
alert(`${title} + this.name`);
}
let lisi = {name : '李四'};
show.call(lisi, '后盾人');3. bind() 方法:
bind() 方法是将函数绑定到某个对象,比如 a.bind(hd) 可以理解为将 a 函数绑定到 hd 对象上,即 hd.a()。
与 call/apply 不同,bind 不会立即执行,他是复制函数行为,会返回新函数。
// bind 是复制函数的行为:
let a = function(){};
let b = a;
console.log(a == b); // true
let c = a.bind();
console.log(a == c); // false
// 使用 bind 会生成新函数
var xw = {
name : '小王',
gender : '男',
age : 24,
say : function(){
alert(this.name + ',' + this.gender + ',今年' + this.age);
}
}
var xh = {
name : '小红',
gender : '女',
age : 18
}
xw.say.bind(xh)(); // 生成新函数,故后面要用()
xw.say.call(xh);
// 在事件中使用 bind
<body>
<button>后盾人</button>
</body>
<script>
document.querySelector('button').addEventListener(
'click',
function(event){
console.log(event.target.innerHTML + this.url);
}.bind({url : 'houdunren.com'})
);
</script>