0

how can i use this of obj in sayHi()

i want this in sayHi to refer to this in obj what changes should i add to sayHi so it prints harry potter instead of undefined

let obj = {
    fullName: "Harry Potter",
    person: {
        sayHi: function(){
            return "This person's name is " + this.fullName
        }
    }
}

is there another way than this obj.person.sayHi.call(obj) or obj.person.sayHi.apply(obj) to do it;

3
  • You could also use bind instead of call. It's a similar concept though: developer.mozilla.org/de/docs/Web/JavaScript/Reference/… Commented Sep 16, 2019 at 11:25
  • 1
    var inside function is private / local scope Commented Sep 16, 2019 at 11:26
  • 1
    you can always change the code to access obj.fullName if you don't want to use call or apply. this in this case points to person. Not sure if that's what you intend to do Commented Sep 16, 2019 at 11:28

4 Answers 4

1

You can use apply()

var obj = {
    fullName: "Harry Potter",
    person: {
        sayHi: function(){
            return "This person's name is " + this.fullName
        }
    }
}

console.log(obj.person.sayHi.apply({fullName: 'John'}))
console.log(obj.person.sayHi.apply(obj))

Sign up to request clarification or add additional context in comments.

Comments

1

Inside sayHi() function the this refers the sayHi function but not the object obj. So in this scenario you can bind the reference this using .call()

var obj = {
    fullName: "Harry Potter",
    person: {
        sayHi: function() {
            return "This person's name is " + this.fullName
        }
    }
}

console.log(obj.person.sayHi.call(obj))

1 Comment

@DavinTryon I think he meant to do -> .bind(obj) instead.
0

No, there isn't. obj contains a reference to the object in it's person property, the object however doesn't know were it is in, it could also be referenced at multiple places.

You could create a reference from person to obj:

obj.person.parent = obj;

Then you can access it as this.parent.

Comments

0

You don't need it, but I think it's more appropriate to use classes for this case.

class Person{
    constructor(fullName){
        this.fullName=fullName;
    }
    sayHi(){
        return "This person's name is " + this.fullName
    }
};
HP = new Person("Harry Potter");
HP.sayHi()

"This person's name is Harry Potter"

2 Comments

I wouldn't say you need to use. But of course doesn't harm in doing so.. :)
This is not the same object from OP. Indeed, you can achieve the same, withou class. just rename obj as person and put sayHi in the same scope as this.fullName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.