问题描述
我正在学习JS中原始数据类型和引用数据类型之间的区别,并且被原始值混淆,因为一方面原始值没有属性或方法,但另一方面我能够执行属性或方法,如length或trim()原始类型(例如John.length或John.toUpperCase())。
I am learning difference between primitive and reference datatypes in JS and am confused by primitive values because on one hand primitive values have no properties or methods but on the other hand I am able to perform properties or methods like length or trim() on primitive types (e.g "John".length or "John".toUpperCase()) .
推荐答案
他们没有。
原始值既没有属性也没有方法。
They don't.Primitive values have neither properties nor methods.
但是当你这样做时
var s = " a ";
var b = s.trim();
s
的值被提升为 String
仅用于此操作的对象(不是原始字符串)。
the value of s
is promoted to a String
object (not a primitive string) just for this operation.
数字和布尔值相同。
您可以使用以下代码检查您是否真的将属性附加到原始值:
You can check you don't really attach properties to primitive values with this code :
var s = "a";
s.prop = 2;
console.log(s.prop); // logs undefined
它记录 undefined
因为该属性附加到临时对象, String
的实例,而不是 s
。如果你想保留房产,你已经完成了
It logs undefined
because the property was attached to a temporary object, an instance of String
, not to s
. If you wanted to keep the property, you'd have done
var s = new String("a");
s.prop = 2;
console.log(s.prop); // logs 2
这篇关于为什么Javascript原始值(例如name =" John")具有属性和方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!