why there is a difference between calling (call) on a method and calling the method on the obj

人走茶凉 提交于 2019-12-14 04:10:16

问题


sorry I really should of asked why there is a differnce ,

`Object.prototype.toString.call(o).slice(x,y);`

and this?

o.toString().slice(x.y);

// why those are different , call should change the 'this' value for the called method // and toString is already inherited ,

var x = 44 ;


`Object.prototype.toString.call(x)`; //"[object Number]"

x.toString(); // '44'

回答1:


You're not calling .call on the method here:

Object.prototype.toString(o).slice(x,y);

Instead, you just call the method (on the prototype object) with o as an argument.

To get an equivalent method to call to

o.toString().slice(x.y);

(which calls the method on the o object, with no arguments), you will need to use

o.toString.call(o).slice(x.y);

Why is x.toString() different from Object.prototype.toString.call(x)?

Because x = 44 is a number, and when you access x.toString you get the Number.prototype.toString method not the Object.prototype.toString method. You could also write

Number.prototype.toString.call(x)

to get "44".




回答2:


Use second one and check the difference between a class (your first case) and an instance of that class (second case).

http://en.wikipedia.org/wiki/Instance_(computer_science)

Its a general object oriented programming issue common for all languages.

  • First is the general definition of the type (without any specific data) - you call it wrong
  • The second one is a particular instance with own data (can be multiple)

Anyway: Object.prototype.toString(o) returns "Object object" so it's not working for you well.




回答3:


The first one (Object.prototype.toString) calls the built in or default toString function for objects, the second calls the toString function of o, which may or may not have been overwritten

var o = {};
o.toString();
    // "[object Object]"
o.toString = function(){};
o.toString();
    // undefined
Object.prototype.toString.call(o);
    // "[object Object]"

With a number, such as 44, the toString function is different from a objects. Calling the toString function of a variable with the value 44, will actually do Number.prototype.toString.call(). Hence the different output.

a few different types:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString



来源:https://stackoverflow.com/questions/24529890/why-there-is-a-difference-between-calling-call-on-a-method-and-calling-the-met

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!