-3

According to me this is only being used if you need to call constructor like below

var dogObj = function(){
    this.bark = "woof";
}

var dog1 = new dogObj();
console.log(dog1.bark);

Is there any cases where I use this on object literal?

var bark = {
  this.bark = "dog"
}

Is above code valid? If yes,how do I call it?

9
  • 2
    "is above code valid?" Run it! Learn about objects: eloquentjavascript.net/04_data.html . Commented Dec 15, 2015 at 7:04
  • I believe you're looking for var o={msg:'hello world',fn:function(){alert(this.msg)}};o.fn(); Commented Dec 15, 2015 at 7:05
  • @Ultimater maybe? but why use this approach compare to constructor? I was asp.net coder. Commented Dec 15, 2015 at 7:12
  • @Ultimater how can I pass custom message to o object? Commented Dec 15, 2015 at 7:13
  • 1
    call and apply are very clean in my opinion. If you're doing something dirty with it, requiring multiple closures, perhaps bind is what you're looking for. It, in a sense, allows you to "edit" the this context of a function and returns the new edited function without calling it. Thus when you're ready to call it, you can call it the normal way like you usually would with the new context bound to the function. Commented Dec 15, 2015 at 7:33

2 Answers 2

2

you can use

var bark = {
  bark : "dog"
}  

and call it like

console.log(bark.bark)
Sign up to request clarification or add additional context in comments.

3 Comments

so what's the point of using constructer in javascript?
To get Class like behaviour
@JenniferAniston: As the name suggested, it's useful if you need to construct multiple objects with the same structure.
0
this.bark = "woof";

Is not valid.

You have try something like below

var dog = {
  bark : "dog"
}

And then you can access like console.log(dog.bark)

Once you formed any json string you can validate the sting using http://jsonlint.com/ just place your json string and the click on validate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.