Javascript函数中的this,值守无名之辈的独一无二
2024-01-21 07:44:18
我们常说“道法自然”,而Javascript中的this,正是如此。它不是一个凭空捏造的概念,而是Javascript语言设计中对现实世界的一种抽象体现。
在现实世界中,我们每个人都有自己的身份和角色,当我们在不同的场合扮演不同的角色时,我们对事物的理解和处理方式也会有所不同。this在Javascript函数中,就扮演着类似的角色。它指向当前函数执行时的上下文对象,而这个上下文对象,正是函数被调用的方式所决定的。
让我们来举几个例子来加深理解。
-
this作为构造函数
当函数被作为构造函数调用时,this指向它新创建的对象。这意味着,你可以使用this来访问和修改新对象的属性和方法。例如:
function Person(name, age) { this.name = name; this.age = age; } const person1 = new Person('John', 30); console.log(person1.name); // 'John'
在上面的例子中,
Person
函数被作为构造函数调用,创建了一个新的Person
对象。this
指向这个新对象,所以我们可以使用this
来给新对象的name
和age
属性赋值。 -
this作为普通函数
当函数被作为普通函数调用时,this指向函数被调用的对象。这意味着,如果你在一个对象的方法中调用一个函数,this将指向这个对象。例如:
const person = { name: 'John', age: 30, greet: function() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } }; person.greet(); // 'Hello, my name is John and I am 30 years old.'
在上面的例子中,
greet
方法被作为普通函数调用,它被调用于person
对象。因此,this
指向person
对象,我们可以使用this
来访问和修改person
对象的属性和方法。 -
this作为回调函数
当函数被作为回调函数调用时,this指向回调函数被调用的对象。这意味着,如果你在一个对象的事件处理函数中调用一个回调函数,this将指向这个对象。例如:
const button = document.getElementById('button'); button.addEventListener('click', function() { console.log(this); // the button element });
在上面的例子中,当按钮被点击时,回调函数被调用。
this
指向按钮元素,我们可以使用this
来访问和修改按钮元素的属性和方法。 -
this作为箭头函数
当函数被作为箭头函数调用时,this指向它的父作用域中的this。这意味着,如果你在一个对象的箭头函数中调用另一个箭头函数,this将指向这个对象。例如:
const person = { name: 'John', age: 30, greet: () => { const innerGreet = () => { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); }; innerGreet(); } }; person.greet(); // 'Hello, my name is John and I am 30 years old.'
在上面的例子中,
greet
方法被作为箭头函数调用,它被调用于person
对象。因此,this
指向person
对象。innerGreet
函数也是箭头函数,它被调用于greet
函数。因此,this
指向greet
函数中的this
,也就是person
对象。 -
this作为bind函数
当函数被作为bind函数调用时,this指向bind函数的第一个参数。这意味着,你可以使用bind函数来改变函数的上下文对象。例如:
const person = { name: 'John', age: 30 }; const greet = function() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); }; const boundGreet = greet.bind(person); boundGreet(); // 'Hello, my name is John and I am 30 years old.'
在上面的例子中,
greet
函数被作为普通函数调用,它没有被调用于任何对象。因此,this
指向undefined
。我们使用bind
函数来改变greet
函数的上下文对象,将其设置为person
对象。这样,当我们调用boundGreet
函数时,this指向person
对象,我们可以使用this
来访问和修改person
对象的属性和方法。
this在Javascript函数中扮演着至关重要的角色,但它常常作为隐性参数而被人忽视。深入理解this,有助于我们写出更健壮、更优雅的代码。通过本文,希望您能对this有一个更深入的了解,并能灵活地运用它来编写出更优秀的Javascript代码。