2.thisとコンストラクション関数
3208 ワード
1. this
どうしてこれが必要ですか?
ex)
var kim = {
name:'kim',
first_score:10,
second_score:20,
sum_score: function() {
return kim.first_score + kim.second_score;
}
}
kimというオブジェクトがあるとします.kimには、name、first、second要素、sum scoreメソッドが含まれます.
しかし、問題はオブジェクトを修正するときに発生します.
kimオブジェクトの名前をleeに変更する場合は、sum scoreのkimを使用します.first_score + kim.second scoreはleeです.first_score + lee.second scoreで1つずつ置き換えます.
だからthisを使ってメンテナンスを助けます.
var kim = {
name:'kim',
first_score:10,
second_score:20,
sum_score: function() {
return this.first_score + this.second_score;
}
}
これは、オブジェクト内で要素にアクセスすることを意味します.つまり、これ.first scoreは、オブジェクト内のfirst score要素を使用することを表します.
このように、オブジェクト名をkimからleeに変更しても、上記の例のようにkimからleeに変更する必要がなく、非常に便利です.
2.constructor
では、次の例と同じ要素を持つオブジェクトが多いと仮定します.
var lee = {
name:'lee',
first_score:10,
second_score:30,
sum_score: function() {
return this.first_score + this.second_score;
}
}
.
var kim = {
name:'kim',
first_score:10,
second_score:20,
sum_score: function() {
return this.first_score + this.second_score;
}
}
.
var park = {
name:'park',
first_score:40,
second_score:20,
sum_score: function() {
return this.first_score + this.second_score;
}
}
要素のコンポーネントが同じである場合、要素を変更するには、すべてのオブジェクトの内容を変更する必要があります.そのため、要素が印刷された工場を「時計トラック」と呼ぶ.
関数オブジェクトの前にnewを追加するとcounterctorはコンストラクション関数として指定されます.
ex)
function person(name, first_score, second_score) {
this.name = name
this.first_score = first_score
this.second_score = second_score
this.sum_score = function() {
return this.first_score + this.second_score;
}
}
.
console.log(people()); #undefined
function person(name, first_score, second_score) {
this.name = name
this.first_score = first_score
this.second_score = second_score
this.sum_score = function() {
return this.first_score + this.second_score;
}
}
.
console.log(new people());
# person {
name: undefined,
first_score: undefined,
second_score: undefined,
sum_score: [Function (anonymous)]
}
newを貼り付けると、コンストラクション関数として指定され、オブジェクトのコンポーネントが表示されますが、関数は表示されません.このようにnewを書くと構造関数になることを知っています.オブジェクトファクトリを作成する方法を見てみましょう.
金を求める方法とscoreの方法を例に挙げて説明した.
function person(name, first_score, second_score) {
this.name = name
this.first_score = first_score
this.second_score = second_score
this.sum_score = function() {
return this.first_score + this.second_score;
}
}
オブジェクト関数を指定した後、パラメータ(name、first score、second score)に入る値を指定します.
var kim = new person("kim", 10, 20)
次に、オブジェクトに必要なメソッドまたは要素を適用します.
こちらはKimのsum score.
console.log(kim.sum_score());
# 30
このようにコンストラクション関数を使用すると、各オブジェクトの内容を変更する必要がなく、コンストラクション関数の内容を変更するだけでメンテナンスに役立ちます.Reference
この問題について(2.thisとコンストラクション関数), 我々は、より多くの情報をここで見つけました https://velog.io/@minominou/2.-this와-constructorテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol