var Ninja = function() {
this.swingSword = function() {
return true
}
}
Ninja.swingFire = function() {
return true
}
var ninja = new Ninja()
assert(ninja.swingFire()) // undefined
So it's creating a new object of Ninja, but why isn't swingFire included in this situation? Could someone explain why?
Instances created with new will inherit from constructor.prototype, not from the constructor object itself. This will behave as you want:
Ninja.prototype.swingFire = function() {
return true;
}
If you want to know how objects, functions, "classes" and inheritance in Javascript work, you should take a look at this video:
The Definitive Guide to Object-Oriented JavaScript: http://youtu.be/PMfcsYzj-9M
This is the best explanation of object orientation in JS that I have ever seen.
In your case, the following happens:
When you create a new Ninja(), you create a new empty object ({}) with a prototype property that points to the functions's prototype. Then the function Ninja will be called as the constructor for your newly created object. It creates the swingSword function and makes it a method of your object.
The swingFire function will not be assigned to your created object, because it is a method of the function itself, not its prototype. Functions are objects as well, so they can actually have properties.
If an object does not have a certain property or method, it looks at it's prototype. If the prototype has the said property/method, it uses it instead. That means that if you give the prototype a method, every object that uses it can use this method as well. That's why you assign methods to the prototype of a function.
Again: Watch the video and you will understand this explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With