먼저, 당신은 generalClass
및 $this
당신의 전 var
(또는 let
, 또는 const
)을 넣어해야합니다. 그와 마찬가지로
는 :
(function() {
"use strict";
var generalClass = function() {
this.ip = false; // page page
this.ie = false; // IE
this.pp = false; // portfolio page
this.om = false; // organize menu
this.wc = false; // shop
this.sh = false; // side header
// So we can get the correct $this if needed
var $this = this;
this.__init();
};
generalClass.prototype = {
__init: function($check) {
console.log('$this', $this);
// Run functions
$this.__format();
$this.__resize();
}
}
var instance = new generalClass();
}());
는
가 무엇 이제 어떻게 (.. 내가 클래스의 인스턴스를 생성 그래서 인생을 내가 콘솔 플러스에서 실행 할 수 $(document).ready()
변경)? $this
안에 __init()
이 정의되어 있지 않습니다. 안에 $this
을 정의해야하지만 여기에 문제가 있습니다. 할당 할 대상은 무엇입니까?
__init()
의 예에서 $this
대신 실제로 this
을 호출 할 수 있지만 이미 지적했듯이 항상 가능한 것은 아닙니다. 그래서 한, 당신으로하십시오 할
다음
(function() {
var GeneralClass = function() {
this.foo = [1, 2, 3];
this.bar = 4;
this.baz = [5];
};
GeneralClass.prototype.someFunction = function() {
console.log('foo', this.foo); // [1, 2, 3]
console.log('bar', this.bar);
var self = this; // storing reference to *this* (oobject for later)
this.baz.forEach(function (item) {
console.log('baz?', this.baz); // undefined, because *this* means here this.baz, and there is no this.baz.baz
console.log('baz!', self.baz); // [5]
});
console.log('foo * bar');
this.foo.forEach(function (item, index) {
console.log('item', index, 'value', item * self.bar);
});
console.log('Both accesible here', this.bar, self.bar);
};
var generalClassInstance = new GeneralClass();
generalClassInstance.someFunction();
}());
I 할당 this
개인적으로, 나는 $(this)
에 대한 $this
를 사용하는 거라고하지만, 그것은 단지 협약 (self
에 :
그러나 좀 더 추상적 인 예제를 설명하자 너는 일관성이있어.) 이제 내 함수 내부에서 호출 된 함수는 에 대한 참조로 작동하는 self
을 사용할 수 있습니다. 하위 함수에서 다른 함수를 호출하면 여전히 GeneralClass
의 this
을 가리 킵니다.
주로 관심있는 내용이 맞기를 바랍니다.
출처
2016-08-26 18:48:03
Seb
처음부터 무엇을하려고합니까? – Hackerman
가능한 복제본 [javascript - 프로토 타입 정의 함수에서 private 멤버 변수에 액세스] (http://stackoverflow.com/questions/436120/javascript-accessing-private-member-variables-from-prototype-defined-functions) – JJJ
확인 이 대답은 ** "엄격한"사용 ** 모드와 관련이 있습니다 : [JavaScript에서 "엄격한 사용"은 무엇입니까? 그리고 그 이유는 무엇입니까?] (http://stackoverflow.com/a/11496488/2247494) – jherax