Reputation: 1340
How to pass values to super class constructors in Javascript.
In the following code snippet
(function wrapper() {
var id = 0;
window.TestClass = TestClass;
function TestClass() {
id++;
this.name = 'name_' + id;
function privateFunc() {
console.log(name);
}
function publicFunc() {
privateFunc();
}
this.publicFunc = publicFunc;
}
function TestString() {
this.getName = function() {
console.log("***" + this.name + "****************");
}
}
TestClass.prototype = new TestString();
})();
How do I pass values to the TestString constructor? Currently, the super class method is using value using 'this' keyword. Is there a way to directly pass values to the super class constructor. Also, I want to see a simple example of extending String. That would demystify a lot of things.
Upvotes: 0
Views: 96
Reputation: 490233
You can use the following code in the constructor of TestClass()
.
TestString.apply(this, arguments);
This will call the constructor with the new object as its context.
However, note that establishing the [[Prototype]]
chain with TestClass.prototype = new TestString();
will have already called the constructor once.
I want to see a simple example of extending
String
.
You can augment its prototype
property.
String.prototype.endsWidth = function(str) {
return this.slice(-str.length) === str;
};
Upvotes: 2