function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
const greet = name => `Hello, ${name}`;
const add = (a, b) => a + b;
console.log(greet("Bob"));
作用域和函数内部变量的持久化
The this
keyword refers to the context in which a function is executed. The value of this
is not determined by how a function is defined, but rather by how it's called.
this
refers to the global objectwindow
objectglobal
objectconsole.log(this); // window (in browser)
this
depends on how the function is calledthis
is the global object (in non-strict mode)this
is undefined
if not explicitly setfunction showThis() {
console.log(this);
}
showThis(); // window (in browser, non-strict mode)
this
refers to the object that owns the methodconst user = {
name: 'John',
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
user.greet(); // "Hello, I'm John"
new
, this
refers to the newly created instancefunction User(name) {
this.name = name;
}
const john = new User('John');
console.log(john.name); // "John"
this
typically refers to the element that received the event