HelloRacoon
HelloRacoon

Reputation: 97

object use own method in javascript

can object define property to use own method?

litk this

obj = {
    prt:function(){console.log("HELLO")}
    prt0:obj.prt()
}

I want obj.prt0 -> "HELLO"

Upvotes: 1

Views: 73

Answers (2)

Jian Zhong
Jian Zhong

Reputation: 501

var obj = {
    prt:function(){
        console.log("HELLO")
        return "HELLO";
    },
    prt0: function(){
        this.prt()
    }
}
obj.prt0;    //do nothing, it is only a method
obj.prt0();  //execute method, will print Hello

Upvotes: 3

Jack Bashford
Jack Bashford

Reputation: 44087

If you want obj.prt0 to have the value of "HELLO", then you're going about it the right way - use this to make it easier, and make sure you return from the function. Also you need to define prt0 after the object is created:

let obj = {
  prt: function() {
    console.log("HELLO");
    return "HELLO";
  }
};

obj.prt0 = obj.prt();

console.log(obj.prt0);

The above does call obj.prt to create the value. If you want prt0 to be a reference to prt - so if you call prt0 it calls prt, you can just do this:

let obj = {
  prt: function() {
    console.log("HELLO");
    return "HELLO";
  }
};

obj.prt0 = obj.prt;

console.log(obj.prt0());

The above will also call console.log("HELLO") twice.

Upvotes: 1

Related Questions