First of all, if you want to use strict-mode, then you have to put var
(or let
, or const
) before your generalClass
and $this
.
Like that:
(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();
}());
(I changed $(document).ready()
to IIFE so I could run it in console. Plus, I created instance of your class.)
What happens now? $this
inside __init()
is not defined. You would have to define $this
inside __init()
but here is the problem: what should be assigned to it?
In your example of __init()
you could actually call this
instead of $this
but as you already pointed it’s not always possible.
But let me illustrate it with more abstract example:
(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();
}());
Here I assign this
to self
(personally, I’d use $this
for $(this)
but it’s only a convention so do as you please, as long as you are consistent). Now functions called inside my function can use self
which works as a reference to outer this
. And if I called another function in my sub-function, it would still point to GeneralClass
’s this
.
I hope this is what you were primarily interested in.