Home  >  Article  >  Web Front-end  >  Introduction to closures in JavaScript_javascript tips

Introduction to closures in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:09:151269browse

The so-called closure should refer to: the internal function reads variables outside the current function, that is, the context in which it was created.

Copy code The code is as follows:

function hello(){
var char = "hello,world";
Function print(){
console.log(char);
};
Return print();
}

It should be noted that the print function here refers to the char variable of the external hello function, so here we can return a
Copy code The code is as follows:

hello,world

In a sense, this function should be attributed to scope. Of course, we have no way to directly access char, unless there is an error when we declare this variable. Such as
Copy code The code is as follows:

function hello(){
char = "hello,world";
Function print(){
console.log(char);
};
Return print();
}

Just because there is a var missing.

Copy code The code is as follows:

Here hello becomes a closure. Closures are a special kind of object. It consists of two parts: the function, and the environment in which the function is created. The environment consists of any local variables that were in scope when the closure was created.

Javscript closure and this

It should be noted that there may be problems when reading this and arguments.

Copy code The code is as follows:

function hello(){
This.char = "hello,world";
Function output(){
         char = "I'm no hello world";        
         console.log(this.char);
};
Return output();
}

Of course, this example is not appropriate enough, so we need an additional example to explain this problem. Here is an example from "Javascript Advanced Programming" to illustrate this problem.
Copy code The code is as follows:

var name = "The window";

var object = {
name: "My Object",

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


It's just that this usage is real, and the solution is to save a temporary variable that, as mentioned in the article "Some knowledge about this in Javascript".

Copy code The code is as follows:

var name = "The window";
var object = {
name: "My Object",

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


Javscript 클로저와 변수 읽기 및 쓰기
변수를 잘 처리하지 않으면 이러한 변수를 수정할 수도 있다는 점은 주목할 가치가 있습니다.
코드 복사 코드는 다음과 같습니다.

함수 hello(){
var char = "hello,world";
복귀{
​​​​ 세트: 함수(문자열){
               반환 문자 = 문자열;
},
                             인쇄: function(){
console.log(문자)
}
}
}
var say = hello();
say.set('new hello,world')
say.print() // 새로운 Hello World

자바스크립트 클로저 및 성능

MDC 인용

코드 복사 코드는 다음과 같습니다.

일부 특정 작업에 클로저가 필요하지 않은 경우 클로저는 처리 속도 및 메모리 소비를 포함하여 스크립트 성능에 부정적인 영향을 미치기 때문에 불필요하게 다른 함수 내에 함수를 만드는 것은 현명하지 않습니다.

기사에서도 언급됐다.
코드 복사 코드는 다음과 같습니다.

예를 들어, 새 개체나 클래스를 만들 때 메서드는 일반적으로 개체의 생성자에서 정의되기보다는 개체의 프로토타입과 연결되어야 합니다. 그 이유는 생성자가 호출될 때마다(즉, 모든 객체 생성에 대해) 메서드가 다시 할당되기 때문입니다.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn