为什么这不是原始的? [英] Why can't this be a primitive?
问题描述
我正在搞乱JavaScript,并注意到这个
永远不会是原始的。我在说什么?让我解释一下。
I was messing around with JavaScript, and noticed that this
can never be a primitive. What am I talking about? Let me explain.
以此函数为例。
function test(){
return typeof this;
}
test.call('Abc'); // 'object'
test.call(123); // 'object'
它们都是'对象'
,而不是'string'
或'number'
,就像我期望的那样。
They are both 'object'
, not 'string'
or 'number'
, like I'd expect.
经过一些混乱(并且弄乱了 instanceof
)后,我发现了正在发生的事情。 'abc'
正被转换为 String
对象, 123
正被转换为 Number
对象。
After a bit of confusion (and messing with instanceof
), I figured out what's going on. 'Abc'
is being coverted to a String
object, and 123
is being converted to a Number
object.
无论如何,我的问题是为什么会发生这种情况,以及如何将对象转换回原语吗?
Anyway, my question is why does this happen, and how do I convert an object back to its primitive?
我知道我可以使用(String)这个
或(Number)这个
,但是如果我不知道这个类型怎么办呢?
I know I could use (String)this
or (Number)this
, but how can I do that if I don't know the type?
编辑:我试图这样做:
function element(){
var $e = $(this),
$d = $e.closest('div');
}
element.call('#myID');
并且无效。 这个
是一个 String
对象,而jQuery只是创建了一个对象集合,而不是使用选择器来搜索DOM。
and it wasn't working. this
is a String
object, and jQuery just made a collection of objects instead of using the selector to search the DOM.
推荐答案
正如其他人所说,根据规范,它被强制转换为对象。
As others noted, it's coerced to an object as per the spec.
需要注意的重要一点是,如果您处于严格模式,则不会发生强制行为。
Important thing to note is that if you're in strict mode, the coercion doesn't happen.
"use strict";
function test(){
return typeof this;
}
test.call('Abc'); // 'string'
test.call(123); // 'number'
所以真正的问题是 为什么不是你使用严格的 ? ; - )
So the real question is why aren't you using strict? ;-)
正如您在评论中指出的那样,您应该可以使用 .valueOf ()
如果你支持不支持严格模式的实现。
As you noted in your comment, you should be able to use .valueOf()
if you're supporting implementations that don't support strict mode.
如果你只是期望一个字符串,或者如果你'也期待一个数字,但你不介意数字字符串,你可以这样做...
If you're only expecting a String, or if you're also expecting a Number, but you don't mind a numeric String instead, you could do this...
(this + '') // "Abc"
(this + '') // "123"
但如果我不知道类型
怎么办?
如果你想知道它的类型,请使用 Object.prototype
上可用的泛型 toString
获取内部 [[Class]] 属性。
If you want to know its type, use the generic toString
available on Object.prototype
to get the internal [[Class]] property.
Object.prototype.toString.call( this ); "[object String]"
Object.prototype.toString.call( this ); "[object Number]"
这篇关于为什么这不是原始的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!