Я лично предпочитаю иметь все содержимое класса в корпусе.
that
не будет иметь MyClass
экземпляр, как установлено в вашем примере.
var MyClass = (function() {
var MyClass = function (config) {
// Optional check whether the class was accessed using new
if (!(this instanceof MyClass))
throw new Error('You must create the instance using the keyword new');
// Don't add it to the prototype as it is unique to the instance
this.config = config;
this.blah();
};
MyClass.prototype = {
blah: function() {
if (this.config.blah)
console.log(this.config.blah);
}
};
return MyClass;
})();
// That has the instance now
var that = new MyClass ({
blah: 'helloWorld'
});
Если вы можете использовать ES6, чем вы могли бы попробовать:
class MyClass {
constructor (config) {
// Don't add it to the prototype as it is unique to the instance
this.config = config;
this.blah();
}
get config() {
return this._config;
}
set config (value) {
this._config = value;
}
blah() {
if (this.config.blah)
console.log(this.config.blah);
}
}
let that = new MyClass({
blah: 'helloWorld'
});
"Лучше" всегда спорно. Я действительно думаю, что это работа, которую вы ставите 'that' и' config' прямо на прототип, а не только на сами экземпляры. Вы можете сделать пример использования синтаксиса ['class'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) в браузерах, которые его поддерживают. На самом деле, это то, что лучше всего подходит для вас. –