admin管理员组

文章数量:1287933

The window.location is an object. But when you execute location.toString() it converts the object to the equivalent to location.href.

My question is how? And can I set up objects to a similar behaviour?

The window.location is an object. But when you execute location.toString() it converts the object to the equivalent to location.href.

My question is how? And can I set up objects to a similar behaviour?

Share Improve this question edited Feb 19, 2015 at 4:34 Timo Tijhof 10.3k6 gold badges37 silver badges53 bronze badges asked Jun 13, 2011 at 10:11 Dean JamesDean James 2,6334 gold badges23 silver badges30 bronze badges 3
  • 1 All objects have a toString() method. You can override it either by changing the prototype implementation, or the implementation for the concrete instance. You should be more precise as to what you want to do. – jjrdk Commented Jun 13, 2011 at 10:14
  • To plement @jjrdk's ment: For window.location, the toString() method is implemented in such a way that it returns the href property. – Tomalak Commented Jun 13, 2011 at 10:20
  • 1 To plement @Tomalak answer, here is the proof developer.mozilla/en-US/docs/Web/API/Location/toString – woto Commented Jun 15, 2022 at 17:41
Add a ment  | 

1 Answer 1

Reset to default 8

You can add a toString method to your object that returns what you want. In that case href

eg:

var obj = {
  href:'',
  toString:function(){
    return this.href;
  }
};

obj.href = 'http://stackoverflow.';
obj.toString();

本文标签: javascriptWhy does locationtoString() report the same as locationhrefStack Overflow