var self = this입니다. 나쁜 패턴?
다음이 필요합니다.
var self = this;
내 자바 스크립트 '클래스'에서 많이. 이것은 일반적으로 수행되지만 약간 잘못된 것 같습니다. 이 질문에서 내가 찾고 싶은 것은 이것을 처리하는 더 나은 방법이거나 이것이 꽤 괜찮습니다.
이것이 올바른 바인딩을 유지하는 표준 방법입니까? 명시 적으로 'this'가 필요하지 않는 한 모든 곳에서 'self'사용을 표준화해야합니다.
편집 : 나는 이것이 왜 필요한지 정확히 알고 있습니다. 나는 그것이 약간 악한 것으로 간주되고 왜 그런지 궁금합니다. 메서드를 호출 할 때 범위를 명시 적으로 정의하는 '적용'기본 제공 자바 스크립트 함수도 있다는 것을 알고 있습니다. 더 낫습니까?
다른 사람들이 말했듯이 :이 "추가 변수"는 (일부 수준에서) this
특수 표현식이므로 변수가 아니라 실행 컨텍스트 / 종료에 묶여 있지 않다는 사실을 알 수있는 유일한 방법 입니다.
그러나 당신이 묻는 것 (또는 내가 정말로 대답하고 싶은 것)은 다음과 같습니다.
var self = this
모든 메서드 / 생성자의 맨 위에 있어야합니까 ?
요약
한 번 시도했지만 같은 질문이 있었지만 더 이상이 방법을 사용하지 않습니다. 이제 클로저에 액세스해야 할 때를 위해 구성을 예약합니다. 나에게 약간의 "이봐,이게 내가 정말 원하는거야!" 내 코드의 의미 :
this -> this
과 self -> this (but really that) in a closure
개별 질문 :
... 이것은 일반적으로 수행되지만 약간 잘못된 것 같습니다. 이 질문에서 내가 찾고 싶은 것은 이것을 다루는 더 좋은 방법이거나 이것이 꽤 괜찮다는 것을 확신시키는 것입니다.
당신에게 옳다고 느끼는 일을하십시오. 한 가지 방법을 시도하고 나중에 다시 전환하는 것을 두려워하지 마십시오 (그러나 각 프로젝트 내에서 일관성을 유지하도록 노력하십시오 :-)
이것이 올바른 바인딩을 유지하는 표준 방법입니까? 명시 적으로 'this'가 필요하지 않는 한 모든 곳에서 'self'사용을 표준화해야합니다.
"self"는 가장 일반적으로 사용되는 이름입니다. 위와 같이 this
클로저 바인딩이 필요한 경우를 제외하고 는 반대의 접근 방식을 선호 합니다.
.. 약간 사악한 것으로 간주되는 경우 및 이유.
악은 (때로는 재미 있지만) 어리석은 주관적인 용어입니다. 나는 그것이 악하다고 말한 적이 없으며, 왜 내가 접근 방식을 따르지 않는지. 어떤 사람들은 내가 세미콜론을 사용하지 않는 것에 대해 "사악하다"고 말합니다. 나는 그들이 실제로 좋은 주장을 내 놓거나 자바 스크립트를 더 잘 배워야한다고 말한다 :-)
메서드를 호출 할 때 범위를 명시 적으로 정의하는 '적용'기본 제공 자바 스크립트 함수도 있다는 것을 알고 있습니다. 더 낫습니까?
문제 apply/call
는 함수 호출 시점에서 사용해야한다는 것입니다. 이미 꺼져있을 수 있으므로 다른 사람 이 귀하의 방법 중 하나를 호출 하면 도움이되지 않습니다 this
. 이 콜백 this
의 요소 / 항목 인 jQuery 스타일 콜백과 같은 작업을 수행하는 데 가장 유용합니다 .
여담으로...
나는 구성원에 대한 "자기 필요"를 피하고 일반적으로 모든 구성원 함수를 this
일반적으로 "예상대로" 수신자 ( )가 "흐르는" 속성으로 승격합니다 .
내 코드의 "private"메서드는 "_"로 시작하며 사용자가 호출하면 해당 메서드에 있습니다. 이것은 또한 객체 생성에 대한 프로토 타입 접근 방식을 사용할 때 더 잘 작동합니다 (실제로 필요함). 그러나 Douglas Crockford 는이 "비공개"접근 방식에 동의하지 않으며 조회 체인이 예기치 않은 수신기를 주입하여 사용자를 방해 할 수있는 경우가 있습니다.
생성자에서 "self"바운드를 사용하면 정확할 수도 있고 아닐 수도 있는 메서드에 대한 조회 체인의 상한이 잠 깁니다 (더 이상 상향 다형성이 아닙니다!). 일반적으로 잘못된 것 같습니다.
즐거운 코딩입니다.
예, 이것이 표준 방법입니다.
Function.apply()
그리고 Function.call()
항상은 아니지만, 도움이 될 수 있습니다.
다음을 고려하세요
function foo()
{
var self = this;
this.name = 'foo';
setTimeout( function()
{
alert( "Hi from " + self.name );
}, 1000 );
}
new foo();
만약 당신이 이것을하고 싶지만 같은 변수의 사용을 피하고 대신 self
사용 call()
하거나 apply()
... 글쎄 ... 당신은 그것을보고 시도하기 시작하지만 곧 할 수 없다는 것을 깨닫습니다. setTimeout()
람다 호출을 담당하므로 이러한 대체 호출 스타일을 활용할 수 없습니다. 여전히 객체에 대한 참조를 보유하기 위해 중간 변수를 생성하게됩니다.
이것이 올바른 바인딩을 유지하는 표준 방법입니까?
JavaScript 및 클래스 / 인스턴스 시스템과 관련된 표준은 없습니다. 선호하는 개체 모델의 종류를 선택해야합니다. 다음은 백그 라운더 에 대한 또 다른 링크입니다 . 결론 : 결론이 없습니다.
일반적으로 var self= this;
클로저에 복사본 (*)을 보관하는 것은 각 메서드의 인스턴스 별 복사본을 사용하여 클로저를 중심으로 구축 된 객체 모델과 함께 진행됩니다. 그것은 일을하는 유효한 방법입니다. 조금 덜 효율적뿐만 아니라 대안에 비해 일반적으로 조금 덜 작품은 객체 모델을 사용하여 프로토 타입을 중심으로 this
, apply()
그리고 인 ECMAScript 5 판의는 bind()
바인딩 방법을 얻을 수 있습니다.
'악'으로 더 많이 계산 될 수있는 것은 동일한 코드에 두 가지 스타일이 섞여있을 때입니다. 불행히도 많은 일반적인 JS 코드가이 작업을 수행합니다 (직면 하자면 아무도 JavaScript의 기괴한 기본 개체 모델을 실제로 이해 하지 못하기 때문입니다 ).
(* : 일반적으로 that
대신 self
사용합니다. 원하는 변수 이름을 사용할 수 있지만 self
이미 window
창 자체를 가리키는 멤버 로서 다소 모호하고 완전히 무의미한 의미를 가지고 있습니다.)
제 동료들이 자기 / 그 변수에 중독 되었기 때문에이 질문을 받았습니다. 왜 그런지 이해하고 싶었습니다.
요즘에는 이것을 처리하는 더 좋은 방법이 있다고 생각합니다 .
function () {}.bind(this); // native
_.bind(function () {}, this); // lodash
$.proxy(function () {}, this); // jquery
In javascript and other languages with closures, this can be a very important thing to do. The object that this
refers to in a method can actually change. Once you set your self
variable equal to this
, then self will reliably remain a reference to the object in question, even if this
later points to something different.
This is an important difference in javascript compared to many other languages we work in. I'm coming from .Net, so this type of thing seemed strange to me at first too.
Edit: Ah, okay, you know all that. (maybe still helpful for someone else.) I'll add that Apply (and Call) are more for using from "the outside", giving to a function you're calling a specific scope that you already know about. Once you're inside a function and you're about to cascade further down into closures, the technique:
var self = this;
is the more appropriate way (easy and clear) way to anchor your current scope.
Most likely this is done as a way to maintain a reference to this
when the scope is about to change (in the case of a closure). I don't know that I'd consider it a bad practice or pattern in and of itself, no. You see similar things a lot with libraries like jQuery and a great deal with working with AJAX.
I think there's an argument to be made for always including var self = this
in every method: human factors.
It's needed often enough that you wind up having a mishmash of methods accessing this
and others using self
for the same purpose. If you move code from one to the other, suddenly you get a bunch of errors.
At the same time, I catch myself absent-mindedly writing self.foo
out of habit when I haven't needed or added a var self = this
. So I think it could make sense to just make a habit of always including it, needed or not.
The only trouble is... this
, self
, or that
are all an ugly pox on your code and I kind of hate them all. So I think it is better to avoid using delegated methods where possible so that you can avoid using this
, that
or self
the vast majority of the time, and use .bind(this)
when you might otherwise resort to self
/that
. It's very rare that using delegates on the prototype is actually going to save you any substantial amount of memory anyway.
A nice side effect of that approach is that you don't have to prefix all your private variables with _
, as they will be truly private and the public properties will be called out by the leading this.
, making your code more readable.
As bobince said, var that = this
is better because it doesn't shadow window.self
. self = this
sounds less awkward to me, but sometimes you get confusing error messages like property myMethod not found on global
, because you forgot the self = this
line.
I just want to point out that 'self' is equivalent to 'window', try outputting window === self to the console. You should use this pattern with 'that' or something similar as a variable name, avoid using 'self' since it is already in use by the browser (one mistake and you will create yourself a global variable). Even though it sounds weird, it is better to use 'that' for its name because other developers will immediately know what you were trying to accomplish in your code, avoid using nonstandard variable names. I believe that this is an important note, but it was only mentioned in one comment, so I wanted to make it more visible.
It's 6 years later, and I have some things to add myself:
bind()
is now common enough to be used everywhere. I use it often as an alternative. Sometimes it feels clearer. I still on occasion use var self = this;
. though.
Arrow functions slowly are becoming viable for usage. The syntax is a bit shorter which is nice, but I think the killer feature really is that by default they always bind to the parent scope.
This:
var self = this;
var foo = function(a) {
return self.b + a;
};
Can now be written as :
var foo = a => this.b + a;
This is the 'most optimistic' usage of arrow functions, but it's pretty sweet.
And just to concluse, there's nothing wrong with:
var self = this;
I like it. It is "self"-explanatory. Douglas Crockford has some things to say about this. He states that using "that" is convention. You can see Crockford for free if you scoot over to yui-theater and watch hes videos about Javascript.
참고URL : https://stackoverflow.com/questions/4371333/is-var-self-this-a-bad-pattern
'IT TIP' 카테고리의 다른 글
nginx 하위 도메인 구성 (0) | 2020.10.19 |
---|---|
Android 장치가 iBeacon으로 작동 할 수 있습니까? (0) | 2020.10.19 |
CSS 패딩이 요소의 크기를 증가시키는 이유는 무엇입니까? (0) | 2020.10.19 |
색상의 유사성을 확인하는 알고리즘 (0) | 2020.10.19 |
C ++ 11 : 가변 템플릿 함수 매개 변수의 수? (0) | 2020.10.19 |