AhMed RaXa
AhMed RaXa

Reputation: 57

Code behaving differently when i return 'this' in the function

I have created an object with an object literal and then created another object with Object.create(car).

var car = {

init: function(sound) { 
    this.sound = sound
    return this
}, 
makeSound: function() {
    console.log(this.sound)
}}

var aventador = Object.create(car).init("whatever")
aventador.makeSound()

The thing i want to know is that when i return this in init function, i can use the code like this:
var aventador = Object.create(car).init("Whatever") aventador.makeSound() and it console logs Whatever

but when i dont return this in the init function, it says undefined
and when i do something like the following:
var aventador = Object.create(car) aventador.init("Whatever") aventador.makeSound() it works even without returning this in the init function.

please explain in details whats happening?

Upvotes: 0

Views: 38

Answers (3)

g.005
g.005

Reputation: 406

The default return value of a function is always undefined. In your case, if init() doesn't return this, then it returns undefined. Obviously when you access something with undefined always throws an error.

Hope that answers your doubt

Upvotes: 0

Jijo Cleetus
Jijo Cleetus

Reputation: 2867

check this, the above statement having 2 parts an object variable called aventador it is assigned with the statement Object.create(car).init("whatever"). In your initial code this statement returning this as the object context. So aventador will get an object instance and it will call the makeSound method. In the second method you are actualy creating the parent object using the statement var aventador = Object.create(car). This will automaticaly create an Object of type car and aventador have an instance of car. so aventador can be used to call both init and makeSound method using the object.

Upvotes: 0

Quentin
Quentin

Reputation: 944201

The functions are properties of an object.

When you return this and use that return value, you get that object. You can then call another function on that object.

When you don't have a return statement, you get undefined. undefined is not that object and the functions are not properties of undefined.

Upvotes: 2

Related Questions