You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中字符串与数字的属性和方法来源疑问

Why do strings and numbers have properties/methods if primitives don't?

Great question! This is one of those classic JavaScript quirks that confuses a lot of new developers—let me break it down simply.

First, you’re totally right: primitive data types (strings, numbers, booleans, null, undefined, symbols, BigInt) don’t have properties or methods of their own. So when you do something like 'hello'.toUpperCase() or 42.toString(), what’s actually happening under the hood?

JavaScript uses a trick called automatic wrapper objects. Here’s the step-by-step breakdown:

  • When you try to access a property or call a method on a primitive value, JS temporarily wraps that primitive in its corresponding object type:
    • Strings get wrapped in a String object
    • Numbers get wrapped in a Number object
    • Booleans get wrapped in a Boolean object
  • This wrapper object has all the built-in properties and methods you’re using (like toUpperCase(), toString(), toFixed()).
  • Once the method/property access is done, JS immediately discards the wrapper object. The original primitive value stays unchanged (since primitives are immutable!).

Let’s take a concrete example to make this clear:

const greeting = 'hi there';
const shoutyGreeting = greeting.toUpperCase();

When we call greeting.toUpperCase(), JS secretly does this:

  1. Creates a temporary String object: new String('hi there')
  2. Calls the toUpperCase() method on this object, which returns 'HI THERE'
  3. Throws away the temporary String object
  4. Assigns the result to shoutyGreeting—the original greeting primitive is still just 'hi there'

You can even test this behavior if you try to add a custom property to a primitive:

let myStr = 'test';
myStr.customProp = 'something';
console.log(myStr.customProp); // Logs undefined!

Why? Because when you set myStr.customProp, you’re actually setting it on the temporary wrapper object that gets created for that line. As soon as that line finishes, the wrapper is gone. When you try to access myStr.customProp next, JS creates a brand new wrapper object—which doesn’t have the customProp you added earlier.

One last thing to note: you can manually create wrapper objects if you want (like new String('hello')), but this is almost never necessary. These wrapper objects are actual object types, not primitives, so they’ll behave differently in checks like typeof or strict equality (===).

Hope that clears up the confusion!

内容的提问来源于stack exchange,提问作者Kostya Hryshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:10:22