khurram
khurram

Reputation: 1070

How do you create a property for a custom object in JavaScript?

I know I can create function for custom object like

var newObj = {
    myFunc1: function () {
        alert('hello');
    },
 myFunc2: function () {
        alert('hello');
    }
}

Now how can I create a new property so that i can set that property in myFunc1 or myFunc2 and and then latter on use it by doing newObj.myProperty.

Upvotes: 1

Views: 81

Answers (4)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

A function on an object can access its other properties via the this keyword.

var newObj = {
                foo : 'Hello There',
                displayValue: function() { alert(this.foo); },
                changeValue: function() { this.foo = 'Goodbye world'; }
             }


newObj.displayValue();
newObj.changeValue();
newObj.displayValue();

This would display "Hello There" followed by "Goodbye world"

Upvotes: 1

Artem Pianykh
Artem Pianykh

Reputation: 1181

You don't have to explicitly define a new property for your object. Just use this.yourNewProperty = "blabla" inside of your function. However, it is a good practise to explicitly define it at the beginning of your object description like yourNewProperty: "", (use any dummy value you need insted of ""), because it realy improves code readability.

Upvotes: 1

jeff
jeff

Reputation: 8348

If I'm interpreting this post right, then you can just do this:

var newObj = {
    propertyHere: "Here's a property.", // custom property
    myFunc1: function () {
        newObj.propertyHere = "Here's a changed property."; // set property
    },
    myFunc2: function () {
        alert(newObj.propertyHere); // get property
    }
}

Upvotes: 1

user1106925
user1106925

Reputation:

var newObj = {
    myFunc1: function () {
        this.greeting = "hello";
    },
    myFunc2: function () {
        alert(this.greeting);
    }
};

newObj.myFunc1(); // set the property on newObj
newObj.myFunc2(); // alert the property on newObj

alert(newObj.greeting); // access it directly from the object

Upvotes: 3

Related Questions