steve
steve

Reputation: 1

object syntax and this in javascript

if i create an object using {} and then try to reference a property, how would i do it?

function Person(){
    this.name : "test";
   }

   var x = new Person();
   alert(x.name);

Upvotes: 0

Views: 106

Answers (3)

John Giotta
John Giotta

Reputation: 16944

my_obj = {name:'john', age:31};
alert(my_obj.name);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Your syntax is off, in your case you simply do this:

function Person(){
    this.name = "test";
    //        ^--- =, not :
}

var x = new Person();
alert(x.name);

If you really want to use object literal syntax, you can, but probably best to avoid it in a constructor function (which is what you have in your code). This works, for instance, but is not the same as your original code:

var Person = {
    name: "test"
};
alert(Person.name);

You can even define functions that way (and people do):

var Person = {
    name: "test",
    speak: function() {
        alert(this.name);
    }
};
Person.speak(); // alerts "test"

...although I'm not fan of doing that because I prefer named functions (that function is anonymous).

Upvotes: 5

SLaks
SLaks

Reputation: 887449

The same way you access any other property.

For example:

alert({ name: -1 }.name);

Your code sample is invalid syntax.
The : character is only used in object literals.

To use properties in constructor (or other) functions, you should use normal assignment:

function Person(){
    var thing = "test";        //Assign a variable
    this.name = "test";        //Assign a property
}
alert(new Person().name);

Upvotes: 0

Related Questions