user2599052
user2599052

Reputation: 1136

properties of object in javascript using this and without this

I have a variable definition like this :

var obj = function(){
this.prop1 = "prop1";
return this;
}

obj.prop2 = "prop2";

I am getting an undefined value when trying to access obj().prop2.

Also , undefined is returned when trying to return obj.prop1 but obj.prop2 return prop2 value.

  1. I want to know the cause of undefined value being returned by obj().prop2.
  2. Is the property prop2 not part of the same object when doing obj.prop2 = "prop2";
  3. Why obj.prop1 returns undefined value.

Upvotes: 1

Views: 103

Answers (2)

David Hellsing
David Hellsing

Reputation: 108500

I am getting an undefined value when trying to access obj().prop2.

This is because obj() returns this, which the context you executed the function with. But you are assigning prop2 to the function object, not the context you are returning.

undefined is returned when trying to return obj.prop1 but obj.prop2 return prop2 value

In your code, obj is a function object, and there is no prop1 property assigned to it. You are assigning prop1 to the context you execute the function with, which is a big difference.

You can execute obj() with another context if you want, that might make more sense:

var obj = function() {
    this.prop1 = 'prop1';
    return this;
}.call({ prop2: 'prop2' });

This will result in: {prop2: "prop2", prop1: "prop1"}

Upvotes: 1

Anand
Anand

Reputation: 14915

If you want this to work(or instanceOf ), you will have to use new. The new key words bounds the this to newly created object whose prototype is function prototype

If you want to work with out this you can write code as following

 var obj = function(propValue){
   return {
        prop1: propValue
    };
}
var objectCheck = obj('prop1');
console.log(objectCheck .prop1);
objectCheck .prop2 = "prop2";
console.log(objectCheck .prop2);

It's simple to understand, the obj function returns an object with property prop1 and then later you add prop2 to that object

Upvotes: 0

Related Questions