ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript のクロージャの概要_javascript のヒント

JavaScript のクロージャの概要_javascript のヒント

WBOY
WBOYオリジナル
2016-05-16 16:09:151228ブラウズ

いわゆるクロージャとは、内部関数が現在の関数の外部、つまり関数が作成されたコンテキストの外部の変数を読み取ることを指します。

コードをコピー コードは次のとおりです:

関数 hello(){
var char = "hello,world";
関数 print(){
console.log(char);
};
戻り print();
}

ここでの print 関数は外部 hello 関数の char 変数を参照しているため、ここでは
を返すことができることに注意してください。
コードをコピー コードは次のとおりです:

こんにちは、世界

ある意味、この関数はスコープに帰属するべきです。もちろん、この変数を宣言するときにエラーが発生しない限り、char に直接アクセスする方法はありません。
など
コードをコピー コードは次のとおりです:

関数 hello(){
char = "hello,world";
関数 print(){
console.log(char);
};
戻り print();
}

var が欠落しているという理由だけで。

コードをコピーします コードは次のとおりです:

ここで hello がクロージャになります。 クロージャは特別な種類のオブジェクトです。これは、関数と関数が作成される環境の 2 つの部分で構成されます。環境は、クロージャの作成時にスコープ内にあったローカル変数で構成されます。

JavaScript クロージャとこれ

これと議論を読むと問題が発生する可能性があることに注意してください。

コードをコピー コードは次のとおりです:

関数 hello(){
This.char = "hello,world";
関数出力(){
char = "私はハローワールドではありません";
console.log(this.char);
};
出力を返します();
}

もちろん、この例は十分に適切ではないため、この問題を説明するには追加の例が必要です。この問題を説明するために、「Javascript Advanced Programming」の例を次に示します。
コードをコピー コードは次のとおりです:

var name = "窓";

var オブジェクト = {
名前: "私のオブジェクト"、

getNameFunc: function(){
return function(){
return this.name;
}
}
};
object.getNameFunc()()


ただ、この使用法は実際に行われており、記事「JavaScript に関するこれに関する知識」で説明されているように、解決策は一時変数を保存することです。

コードをコピーします コードは次のとおりです:

var name = "窓";
var オブジェクト = {
名前: "私のオブジェクト"、

getNameFunc: function(){
var that = this;
return function(){
return that.name;
}
}
};
object.getNameFunc()()


Javscript closures and reading and writing variables
It is worth noting that if we do not handle our variables well, we can also modify these variables.
Copy code The code is as follows:

function hello(){
var char = "hello,world";
Return{
​​​​ set: function(string){
               return char = string;
},
                              print: function(){
console.log(char)
}
}
}
var say = hello();
say.set('new hello,world')
say.print() // new hello world

Javascript Closures and Performance

Quote from MDC

Copy code The code is as follows:

If closures are not required for some specific task, it is unwise to create functions within other functions unnecessarily because closures have a negative impact on script performance, including processing speed and memory consumption.

The article also mentioned.
Copy code The code is as follows:

For example, when creating a new object or class, methods should usually be associated with the object's prototype rather than being defined in the object's constructor. The reason is that this will cause the method to be reassigned every time the constructor is called (that is, for every object creation).
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。