在一个简单的例子中,我们可以看到this对象的作用域如何随着其所在的环境而改变。首先,我们定义一个对象Person,它有一个属性name并且有一个叫introduce的方法。
function Person(name) {
this.name = name;
}
Person.prototype.introduce = function() {
console.log("Hello, my name is " + this.name);
}
var john = new Person("John");
var jane = new Person("Jane");
john.introduce(); // "Hello, my name is John"
jane.introduce(); // "Hello, my name is Jane"
这个例子中,this指向当前的Person实例。当我们调用john.introduce()时,实际上是调用了john这个对象的introduce方法,所以this指向了john。同理,当我们调用jane.introduce()时,this指向了jane。
然而,事情并不总是这么简单,当我们在嵌套函数中使用this时,作用域就不是那么明确了。让我们看下面这个例子。
var student = {
name: "Bob",
courses: ["Math", "Science"],
showCourses: function() {
this.courses.forEach(function(course) {
console.log(this.name + " is enrolled in " + course);
})
}
}
student.showCourses();
在这个例子中,我们尝试打印一个学生的所有课程,但当我们执行代码时发现,控制台输出undefined。这是因为我们在嵌套的函数中使用了this,而这个函数的作用域已经改变了。
为了使这个例子工作,我们需要在嵌套函数之前,将this保存到一个变量中,如下所示。
var student = {
name: "Bob",
courses: ["Math", "Science"],
showCourses: function() {
var self = this;
this.courses.forEach(function(course) {
console.log(self.name + " is enrolled in " + course);
})
}
}
student.showCourses();
现在,变量self保存了外部this的值,因此我们可以在嵌套函数中访问它。
在Javascript中,this的作用域取决于它如何被调用。当我们在全局环境中使用this时,它指的是全局对象。例如:
console.log(this === window); // true
function test() {
console.log(this === window); // true
}
test();
在这个例子中,当我们使用this时,它指的是全局对象window。即使我们在一个函数中使用this,它也指向全局对象,如果函数没有被定义为一个对象的方法的话。
尽管this在Javascript中可能有一些令人困惑的地方,但它是一种非常有用的工具。当我们了解this的作用域时,在代码中使用它将会更加轻松自如。
上一篇:css指定p的宽度
下一篇:css投影代码怎么写









