let user = {
name: "John",
age: 30
};
JavaScript action
user hello
let user = {
name: "John",
age: 30
};
user.sayHi = function() {
alert("Hello!");
};
user.sayHi(); // Hello!
user.sayHi
user.sayHi()
user sayHi
let user = {
// ...
};
//
function sayHi() {
alert("Hello!");
}
//
user.sayHi = sayHi;
user.sayHi(); // Hello!
//
user = {
sayHi: function() {
alert("Hello");
}
};
//
let user = {
sayHi() { // "sayHi: function(){...}"
alert("Hello");
}
};
"function" sayHi()
this
user.sayHi() user name
this
this
let user = {
name: "John",
age: 30,
sayHi() {
// "this"
alert(this.name);
}
};
user.sayHi(); // John
user.sayHi() this user
this
let user = {
name: "John",
age: 30,
sayHi() {
alert(user.name); // "user" "this"
}
};
user admin = user user
let user = {
name: "John",
age: 30,
sayHi() {
alert( user.name ); //
}
};
let admin = user;
user = null; //
admin.sayHi(); // TypeError: Cannot read property 'name' of null
alert this.name user.name
this
JavaScript this JavaScript this
function sayHi() {
alert( this.name );
}
this
this
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
alert( this.name );
}
//
user.f = sayHi;
admin.f = sayHi;
// this
// "this"
user.f(); // Johnthis == user
admin.f(); // Adminthis == admin
admin['f'](); // Admin
obj.f() this f obj this user admin
this == undefinedthis this this
JavaScript this
this
this
this thisthis
arrow() this user.sayHi()
let user = {
firstName: "Ilya",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Ilya
-
object.doSomething() -
this
this
-
thisthis object.method()thisobject
this this
<code><pre>10 plnkrJSBincodepen