JavaScript中的this

66 阅读2分钟

1、Function.prototype.call()

Function 实例的 call()  方法会以给定的 this 值和逐个提供的参数调用该函数。

function Product(name, price) {
    this.name = name;
    this.price = price;
}

function Food(name, price) {
    Product.call(this, name, price);
    this.category = 'food';
}

console.log(new Food('cheese', 5).name);

在上述例子中,Food使用了product的构造函数实现了自身的赋值效果 即Food.name = "cheese"Food.price = 5

2、Function.prototype.apply()

Function 实例的 apply()  方法会以给定的 this 值和作为数组(或类数组对象)提供的 arguments 调用该函数。

const numbers = [1,2,3,4,5];
const max = Math.max.apply(null, numbers);
console.log(max);
const min = Math.min.apply(null, numbers);
console.log(min);

在上述例子中,Math中的maxmin函数通过applynumbers执行,实现了函数的传递和执行

3、Function.prototype.bind()

Function 实例的 bind()  方法创建一个新函数,当调用该新函数时,它会调用原始函数并将其 this 关键字设置为给定的值,同时,还可以传入一系列指定的参数,这些参数会插入到调用新函数时传入的参数的前面。

const module = {
  name: "zhangsan",
  getName: function(){
    return this.name;
  }
};

const getName = module.getName;
console.log(getName());

const bindGetName = getName.bind(module);
console.log(bindGetName());

在上述例子中,第一个输出值为"",第二个输出值为"zhangsan",由此可见,要使用bind将这些this指定起来,作为赋值

4、箭头函数表达式

箭头函数表达式的语法比传统的函数表达式更简洁,但在语义上有一些差异,在用法上也有一些限制:

const animal = ['dog', 'cat', 'fish'];
console.log(animal.map(a => a.search("s")))

上述代码通过mapanimal进行遍历和处理,获取了每个元素中s的位置 通过箭头函数=>可以很方便的进行遍历处理