How can I do inheritance with this example.
I'm trying to create an object literal that functions as a singleton. Within this I'd like to extract my classes. Next to that, these classes should inherit from each other when applicable .
Like so:
var Singleton = {
car: function() {
this.engine= true;
},
ford: function() {
this.color = 'red';
}
};
I'd like to let ford inherit from bar, but I can't do this :
ford: function() {
this.color = 'red';
this.prototype = new this.car();
}
Any ideas?
var Something = {
foo: function() {
this.greet = 'hello';
},
bar: function() {
this.color = 'blue';
}
};
Something.bar.prototype = new Something.foo();
alert((new Something.bar()).greet)
Here is a primer on inheritance
If you are trying to make bar
inherit properties of foo
then you could do something like this (note, that this way you will not have prototype properties inhereted though):
var Something = {
foo: function() {
this.greet = 'hello';
},
bar: function() {
Something.foo.call(this);
this.color = 'blue';
}
};
And then use it like this:
var bar = new Something.bar();
bar.color // blue
bar.greet // hello
You could do something like this:
function Foo() {
this.greet = "hi!";
}
Bar.prototype = new Foo;
function Bar(color) {
Foo.apply(this.arguments);
this.color = color;
}
var myBar = new Bar("red");
A Bar
created this way will have both greet
and color
properties. This method preserves Prototype properties.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.