为什么在方法上调用(call)和在对象上调用方法是有区别的

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

本文关键字:调用 方法 有区别 对象 call 为什么      更新时间:2023-09-26

对不起,我真的应该问一下为什么有区别,

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

这吗?

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

//为什么这些是不同的,调用应该改变'this'值为被调用的方法//和toString已经被继承,

var x = 44 ;

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

您没有在这里的方法上调用.call:

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

相反,您只需以o作为参数调用该方法(在原型对象上)。

获取要调用

的等效方法
o.toString().slice(x.y);

(它调用o对象上的方法,不带参数),您需要使用

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

为什么x.toString()Object.prototype.toString.call(x)不同?

因为x = 44是一个数字,当你访问x.toString时,你得到的是Number.prototype.toString方法而不是Object.prototype.toString方法。你也可以写

Number.prototype.toString.call(x)

获取"44" .

使用第二个,并检查一个类(你的第一种情况)和该类的实例(第二种情况)之间的区别。

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

这是所有语言中常见的面向对象编程问题。

  • 首先是类型的一般定义(没有任何具体数据)-你叫错了
  • 第二个是具有自己数据的特定实例(可以是多个)

:Object.prototype. tostring (o)返回"Object Object ",所以它不能很好地为你工作

第一个(Object.prototype.toString)调用对象的内置或默认toString函数,第二个调用o的toString函数,该函数可能被覆盖,也可能没有被覆盖

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

对于数字,如44,toString函数不同于对象。调用值为44的变量的toString函数实际上会执行Number.prototype.toString.call()。因此有不同的输出。

几个不同的类型:

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