Function.prototype.call()
语法:function.call(thisArg, arg1, arg2, …)
用法:
- 使用 call 方法调用父构造函数
- 修改匿名函数中的 this
- 调用函数并且指定上下文的 this
1.使用 call 方法调用父构造函数
例子:
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name1, price1) {
Product.call(this, name1, price1);
this.category = 'food';
}
function Toy(name2, price2) {
Product.call(this, name2, price2);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
console.log(cheese)
console.log(fun)
2.修改匿名函数中的 this
例子
<script>
var animals = [{
species: 'Lion',
name: 'King'
},
{
species: 'Whale',
name: 'Fail'
}
];
for (var i = 0; i < animals.length; i++) {
(function (i) {
this.print = function () {
console.log('#' + i + ' ' + this.species +
': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
</script>
3.调用函数并且指定上下文的 this
<script>
function doctor() {
var output = this.name + "最近得了" + this.illness
console.log(output)
}
var obj = {
name: "西西卡",
illness: "糖尿病"
};
greet.call(obj); // 西西卡最近得了糖尿病
</script>
在例子中,使obj调用了doctor()函数,并使doctor()中的 this 指向了obj
4.使用 call 方法调用函数并且不指定第一个参数(argument)
在非严格模式下, call 指向了 window
var sData = "哥哥";
function display() {
console.log("我是你" + this.sData);
}
display.call();
在严格模式下,call( )会将原本指向window的指向转为指向undefined。
Function.prototype.apply()
语法:func.apply(thisArg, [argsArray])
1.apply 可以将数组打散成单个元素再添加进新数组
例子:
var arr1 = ['a', 'b'];
var arr2 = [0, 1, 2];
arr1.push.apply(arr1, arr2);
console.info(arr1); // ["a", "b", 0, 1, 2]
2.将数组打散后再使用其他本不支持数组的内置函数
/* 找出数组中最大/小的数字 */
var numbers = [5, 6, 2, 3, 7];
/* 应用(apply) Math.min/Math.max 内置函数完成 */
var max = Math.max.apply(null, numbers);
/* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
var min = Math.min.apply(null, numbers);
console.log(max)
console.log(min)
使用apply来链接构造器
Function.prototype.construct = function (aArgs) {
var oNew = Object.create(this.prototype);
this.apply(oNew, aArgs);
return oNew;
};
Function.prototype.bind()
语法:function.bind(thisArg[, arg1[, arg2[, …]]])
1.创建绑定函数
<script>
this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象
var module = {
x: 81,
getX: function() {
return this.x;
}
};
console.log(module.getX()) // 81
var getX = module.getX;
console.log(getX())
// 返回 9 - 因为函数是在全局作用域中调用的
// 创建一个新函数,把 'this' 绑定到 module 对象
// 新手可能会将全局变量 x 与 module 的属性 x 混淆
var b_GetX = getX.bind(module);
console.log(b_GetX()) // 81
</script>