关于JS中的this
function fruits() {
}
fruits.prototype = {
color: 'red',
age: '30',
say: function() {
return this.color;
}
};
var fru = new fruits();
console.log(fru.say());
/*********************************/
banana = {
color: 'yellow'
};
console.log(fru.say.call(banana));
//如果一个对象上面没有方法的话,可以用call,apply调用其他对象的方法,来改变 //this的上下文
/*********************************/
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
//用push模拟concat
Array.prototype.push.call(arr1, arr2); //[1,2,3,[4,5,6]]
Array.prototype.push.apply(arr1, arr2); //[1,2,3,4,5,6]
console.log(arr1);
/*********************************/
var num = [1, 2, 3, 4, 5];
//获取数组中的最大值和最小值
var maxInnum = Math.max.apply(Math, num); //5
var maxInnum1 = Math.max.call(Math, 5, 1, 6, 3, 0); //6
console.log(maxInnum1);
/*********************************/
//让类数组有数组的方法
var domNodes=Array.prototype.slice.apply(document.getElementsByTagName("*"));
console.log(domNodes.push(1));
/*********************************/
function log() {
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
}
log(10, 'aa');
log(5, 1);
/*********************************/
var foo = {
bar: 1,
event: function() {
document.getElementById('box').onclick = function() {
alert(this.bar);
}.bind(this);
}
};
foo.event();
/*********************************/
var bar1 = function() {
console.log(this.x);
};
var foo1 = {
x: 3
};
var foo2 = bar1.bind(foo1);
foo2();
/*********************************/
var bar2 = function() {
console.log(this.x);
};
var foo3 = {
x: 10
};
bar2.call(foo3);
bar2.apply(foo3);
bar2.bind(foo3)();
/*********************************/
//验证是否是数组(前提是toString()方法没有被重写过)
functionisArray(obj){
returnObject.prototype.toString.call(obj) === '[object Array]' ;
}
/*********************************/
区别是,当你希望改变上下文环境之后并非立即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会立即执行函数。
再总结一下:
- apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
- apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
- apply 、 call 、bind 三者都可以利用后续参数传参;
- bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

浙公网安备 33010602011771号