Nora
Nora

Reputation: 65

How can I access this property based on this javascript code?

Example, lets say I have the following Constructor function defined in window global of a browser.

function AccessProperty() {
  this.myName = "Chris";
}

Now I execute this function like this:

new AccessProperty();

Now based on how I executed the function above with the new keyword, how can I access this.myName property without adding something like this:

var acccess = new AccessProperty();

Upvotes: 0

Views: 61

Answers (3)

Mark
Mark

Reputation: 92460

It's really not clear what your ultimate goal is. this is a contextual reference that changes depending on the context of a function. When you use new, this refers to an object the js system creates for you and returns to the caller. Without new this will be the global window if you just call the function.

You can explicitly tell the function what this is with a function like call():

function AccessProperty() {
    this.myName = "Chris";
  }

let someObject = {}
AccessProperty.call(someObject)   // this will be someObject
console.log(someObject.myName)    // to which the function adds myName.

But that's seems like the hard way to do something, when you could just use new and get an object with a myName property.

As a demonstration of the dynamic nature of this consider the code:

function AccessProperty() {
  this.myName = "Chris";
}

let o = {
  set: AccessProperty,
  talk() {console.log(this.myName)}
}
// because of the way it's called `this` in
// the function AccessProperty will be
// the object o 
o.set()   
o.talk()
console.log(o) // o now has a myName property

This behavior is very useful in some situations, if you don't want that behavior you are required to use this you can just define variables.

Upvotes: 1

Abhijet
Abhijet

Reputation: 165

If you are not in strict mode you can do something like this

function AccessProperty(){
 this.name="ram"
}

function parent(){
  AccessProperty.bind(this)
  AccessProperty()
  console.log(this.name)
}


parent()

Here we have binded the scope of AccessProperty function to the scope of parent function. With this done the name will be in the scope of parent function

Upvotes: 0

HugoTeixeira
HugoTeixeira

Reputation: 4884

You can access it directly like this:

acccess.myName

or use the square brackets:

acccess['myName']

Without using the new operator

If you call that function without the new operator, the property will be set in the window object of the page. This is not very recommended, but you could do:

AccessProperty();
console.log(window.myName);

Another possibility is to return a new object like this:

function AccessProperty() {
    return { myName: "Chris" };
}
var o = AccessProperty(); // not using 'new'
console.log(o.myName);

Upvotes: 3

Related Questions