Sunday 15 June 2014

How do I assign the return value from a method to another object property in Javascript? -


I am objectively partaking some old code in JavaScript, and I'm afraid that I know a little bit bugger How is that properties defined, and I know how to define methods, but what if I want to assign return value to any method as property?

I have supplied the code from Chrome's error message console. I can not see what I am doing, but the console is telling me that I am either trying to do something in the global scope, or anything or nothing. Here it is:

Code:

  var testobj = {a: 2, b: 4, c: function () {return.a * this.b; }, D: this.c (), // OK, got it, it is trying to call it with a global radius Fine. E: function () {if (this.d) {console.log ("success"); Console.log (this.d); } And {console.log ("Error"); }}}   

Error:

  typeError: There is no way in object [object global] 'c'   < P> New code:  
  var testobj = {a: 2, b: 4, c: function () {this.a * this.b return]; }, D: testobj.c (), // But if I change it like this, it still does not work. what gives? E: function () {if (this.d) {console.log ("success"); Console.log (this.d); } And {console.log ("Error"); }}}   

New error:

  typeError: can not call 'c' the undefined method   

Anybody can see what I am doing?

You can fix this by using:

  var Testobj = {a: 2, b: 4, c: function () {return.a * this.b; }, D: function () {return.c (); }, E: function () {if (this.d) {console.log ("SUCCESS"); Console.log (this.d); } And {console.log ("Error"); }}}   

The reason for this is because when you D: this.c () , does actually have a global object When creating your testobj , the radius is a global object, so this is a global object.

If you use

  d: function () {this.c (); }   

You are just setting testobj.c for a certain function. When you call this that function is evaluated d so when you call d , it will see the scope You will see that this scope is testobj . And testobj has a c function, this wall calls and returns it.

I have kept it to see it in implementation. / P>

No comments:

Post a Comment