7

From what I understand, the former will:

  1. Find the toString method on Object
  2. call it on value but with this bound to value

And value.toString() will.

  1. Find the toString method somewhere in value's prototype chain
  2. Call toString on value bound with this as value via the function invocation pattern

So the difference is if there is an overridden toString method in value... it will use that.

My question is:

  1. Is that the only difference?
  2. Conversely, is this pattern the standard pattern to use if we want to be guaranteed we're calling Parent's method and not potentially some overridden by Child? (In this case Parent = Object, Child = the class value comes from, if we're thinking classically, and method = toString.)
4

3 回答 3

6

Object.prototype.toString.apple(value)会让你调用null,当你使用null.toString()时,它会产生错误。

Object.prototype.toString.apply(null);
>"[object Null]"

null.toString();
>TypeError: Cannot call method 'toString' of null
于 2013-03-06T01:44:47.487 回答
5

Object.prototype.toString可以是一种不同的方法,而不是value.toString()取决于后者是什么。

> Object.prototype.toString.apply("asdfasdf")
"[object String]"
> "asdfasdf".toString()
"asdfasdf"
> Object.prototype.toString.apply(new Date)
"[object Date]"
> (new Date).toString()
"Tue Mar 05 2013 20:45:57 GMT-0500 (Eastern Standard Time)"

.prototype[function].apply(或.call.bind)允许您更改方法的上下文,即使上下文可能根本没有这样的方法。

var o = {};
o.prototype = {x: function () { console.log('x'); }}
var y = {}
o.prototype.x.call(y)
y.x(); //error!

……也就是说

  1. 这不是唯一的区别
  2. 这不一定与父子关系.. 它只是允许您使用不同的对象上下文调用一个对象的方法(或任何函数)。
于 2013-03-06T01:49:01.767 回答
2

是的,你没看错。我通常不会看到人们Object.prototype.toString像这样直接调用(让对象覆盖他们的方法通常是有意义的toString),但它肯定非常常见,并且推荐用于其他一些方法,例如Object.prototype.hasOwnProperty.

于 2013-03-06T01:43:19.343 回答