1

can object define property to use own method?

litk this

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

I want obj.prt0 -> "HELLO"

Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
asked May 14, 2019 at 2:50

2 Answers 2

3
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
Samyak Jain
9401 gold badge10 silver badges12 bronze badges
answered May 14, 2019 at 3:00
Sign up to request clarification or add additional context in comments.

2 Comments

i don't wanna use another methods. Isn't there any way to use only property? and why property cant approach own methods? even use this.method
That depends on what you want to achieve. Because the prt is a function, and it can accept params, you need type () after the function name. If you only want a value, you can use a attribute, like var obj = { prt: 'HELLO'} the use obj.prt, BTW, call a function is simple and clear. why don't you want to use it, you
1

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.

answered May 14, 2019 at 2:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.