问题
I am trying to emulate inheritance in javascript using a the Lo-Dash javascript library.
I am simply using _.extend to do so:
function Parent() {
var self = this;
self.hello = function () {
console.log('Hello from parent');
};
}
function Child() {
var self = this;
_.extend(self, Parent);
}
Child.hello(); // Doesn't exist
I thought this would work since all javascript functions are objects but obviously I am wrong. Why doesn't this work and how would I properly emulate inheritance using Lo-Dash?
回答1:
Parent is simply the constructor for the Parent class, it does not itself have the hello
property that it adds to self
. You could just change the _.extend
line to this: _.extend(self, new Parent())
to solve it. This works because the object returned by new Parent()
does have a hello
property that _.extend
can copy over to self
.
To access the hello
property you will also have to create an instance of the Child
class rather than accessing hello
on the constructor. After making the above change, (new Child()).hello()
should work because you accessing the hello
property on the Child
instance not the constructor.
But, this seems to me to be a poor solution because new Child() instanceof Parent
will return false
. If you want to properly set up the prototype chain so there is "true" inheritance going on you should read about psuedoclassical and prototypal inheritance.
回答2:
See _.create documentation for a working example.
回答3:
You could use _.create() function and prototype
to emulate inheritance.
function Parent() {}
Parent.prototype.hello = function() {
console.log('Hello from parent');
};
function Child() {}
Child.prototype = _.create(Parent.prototype, {
'constructor': Child
});
var child = new Child();
child.hello(); //Hello from parent
来源:https://stackoverflow.com/questions/25149713/inheritance-with-lo-dash