2

I tried in my chrome debug console:

>function m(){function toString(){return "abc"}}
undefined
>new m().toString()
"[object Object]"

I expect it to print "abc". Why?

2
  • A function used as a constructor should return an object. If it doesn't, the return value is ignored and an object is returned instead. Commented Sep 1, 2016 at 7:37
  • You need to learn the difference between local variables and object properties. Commented Sep 1, 2016 at 7:39

3 Answers 3

4

You are not using your own toString method (which is a private function inside of m), but the one from Object.

For your own method, you need to assign your toString method to m's prototype, like

m.prototype.toString = function () { return 'abc'; };

function m() {}
m.prototype.toString = function () { return 'abc'; };

console.log((new m).toString());

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

Comments

2

try this.

function m() {
  this.toString = function() {
    return "abc";
  }
}

var m1 = new m();
alert(m1.toString());

Comments

0

Your code is wrong. You can try this code and check output here http://jsbin.com/luremulano/edit?html,js,console,output

  console.log(m('abc'));

  function m(a){
      return a.toString();  
  }

Comments

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.