Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do objects work in JavaScript?

Tags:

javascript

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?

like image 890
Strawberry Avatar asked Jul 26 '26 17:07

Strawberry


2 Answers

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;
}
like image 121
bfavaretto Avatar answered Jul 29 '26 08:07

bfavaretto


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.

like image 41
Butt4cak3 Avatar answered Jul 29 '26 08:07

Butt4cak3