Wednesday, May 15, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  128] [ 2]  / answers: 1 / hits: 24451  / 10 Years ago, tue, june 24, 2014, 12:00:00

I am trying to use OOP based javascript/jQuery. I want to put all my JS function inside a class, so it can be easily overridden/hooked.



I tried with a simple OOP code, but its giving type error: not a constructor.
Please have a look at my code and guide me what is wrong in my code, and how to fix it.



var myTestClass = {
testAttribute : 'test', // atttribute
testMethod : function(){ alert( testAttribute); }
};

var my = new myTestClass();
my.testMethod();


Thanks


More From » jquery

 Answers
6

to view your alert:



var myTestClass = {
testAttribute: 'test',
testMethod: function () { alert(this.testAttribute); }


};


myTestClass.testMethod();


another approach:



function myTClass(){
var testAttribute = 'test';
this.testMethod = function () {
alert(testAttribute);
};

}

var obj = new myTClass();
obj.testMethod();


Lazy Inheritance example:



function myTClass(){

this.testMethod = function () {
alert(this.testAttribute);
};

}

myTClass.prototype.testAttribute = 'test';

var obj = new myTClass();
obj.testMethod();

function derivedTClass() {
myTClass.call(this);
this.testMethod = function () {
alert('derived ' + this.testAttribute);
};
}

derivedTClass.prototype = Object.create(myTClass.prototype);

var obj2 = new derivedTClass();
obj2.testMethod();

derivedTClass.prototype.constructor = derivedTClass;

[#70455] Sunday, June 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rafael

Total Points: 5
Total Questions: 103
Total Answers: 103

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;