:
let user = {
name: "John",
age: 30
};
: .
JavaScript (method ).
user :
let user = {
name: "John",
age: 30
};
user.sayHi = function() {
alert("Hello!");
};
user.sayHi(); // Hello!
Here weve just used a Function Expression to create a function and assign it to the property user.sayHi of the object.
Then we can call it as user.sayHi(). The user can now speak!
A function that is a property of an object is called its method.
So, here weve got a method sayHi of the object user.
:
let user = {
// ...
};
//
function sayHi() {
alert("Hello!");
};
//
user.sayHi = sayHi;
user.sayHi(); // Hello!
/ ([object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming) "OOP").
OOP . Design Patterns: Elements of Reusable Object-Oriented Software E.Gamma R.Helm R.Johnson J.Vissides Object-Oriented Analysis and Design with Applications G.Booch .
:
//
user = {
sayHi: function() {
alert("Hello");
}
};
//
user = {
sayHi() { // same as "sayHi: function()"
alert("Hello");
}
};
"function" sayHi() . ( ) . .
this
. user.sayHi() user.
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
this.name user.name alert .
In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function, even if its not a method of an object.
this JavaScript . .
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;
// t
// "this"
user.f(); // John (this == user)
admin.f(); // Admin (this == admin)
admin['f'](); // Admin ( )
: obj.f() this obj f user admin .
this == undefined:
function sayHi() {
alert(this);
}
sayHi(); //
this undefined . this.name .
this ( window ). "use strict".
. this .
this this this .
this JavaScript .
this . . .
"this
(Arrow function) : this . this this .
arrow() this user.sayHi():
let user = {
firstName: "Ilya",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Ilya
this . .
- (methods).
-
object.doSomething(). - ( )
this. -
this. -
this. - .
-
object.method()thisobject.
this . this .
<code><pre>10 (plnkr, JSBin, codepen)