原生函数

# 原生函数

JavaScript 的内建函数(built-in function),也叫原生函数(native function),如 String 和 Number

• String()

• Number()

• Boolean()

• Array()

• Object()

• Function()

• RegExp()

• Date()

• Error()

• Symbol()——ES6 中新加入的!

var a = new String( "abc" );
typeof a; // 是"object",不是"String"
a instanceof String; // true
Object.prototype.toString.call( a ); // "[object String]"
1
2
3
4

通过构造函数(如 new String("abc"))创建出来的是封装了基本类型值(如 "abc")的封装对象

# 3.1 内部属性 [[Class]]

所有 typeof 返回值为 "object" 的对象(如数组)都包含一个内部属性 [[Class]]

这个属性无法直接访问,一般通过 Object.prototype.toString(..) 来查看。

Object.prototype.toString.call( [1,2,3] );
// "[object Array]"
Object.prototype.toString.call( /regex-literal/i );
// "[object RegExp]
1
2
3
4
Object.prototype.toString.call( null );
// "[object Null]"
Object.prototype.toString.call( undefined );
// "[object Undefined]"
1
2
3
4

“包装”

Object.prototype.toString.call( "abc" );
// "[object String]"
Object.prototype.toString.call( 42 );
// "[object Number]"
Object.prototype.toString.call( true );
// "[object Boolean]"
1
2
3
4
5
6

# 3.2 封装对象包装

由 于 基 本 类 型 值 没 有 .length和 .toString() 这样的属性和方法,需要通过封装对象才能访问,此时 JavaScript 会自动为基本类型值包装(box 或者 wrap)一个封装对象

浏览器已经为 .length 这样的常见情况做了性能优化,直接使用封装对象来“提前优化”代码反而会降低执行效率

# 3.3 拆封

如果想要得到封装对象中的基本类型值,可以使用 valueOf() 函数:

var a = new String( "abc" );
var b = new Number( 42 );
var c = new Boolean( true );
a.valueOf(); // "abc"
b.valueOf(); // 42
c.valueOf(); // true
1
2
3
4
5
6
var a = new String( "abc" );
var b = a + ""; // b的值为"abc"
typeof a; // "object"
typeof b; // "string"
1
2
3
4

# 3.4 原生函数作为构造函数

构造函数 Array(..) 不要求必须带 new 关键字。不带时,它会被自动补上。

Object(..)、Function(..) 和 RegExp(..)

Date(..) 和 Error(..)

Symbol(..)

原生原型

原生构造函数有自己的 .prototype 对象,如 Array.prototype、String.prototype 等。

• String#indexOf(..)

在字符串中找到指定子字符串的位置。

• String#charAt(..)

获得字符串指定位置上的字符。

• String#substr(..)、String#substring(..) 和 String#slice(..)

获得字符串的指定部分。

• String#toUpperCase() 和 String#toLowerCase()

将字符串转换为大写或小写。

• String#trim()

去掉字符串前后的空格,返回新的字符串。

以上方法并不改变原字符串的值,而是返回一个新字符串。

所有的函数都可以调用 Function.prototype 中的 apply(..)、call(..) 和 bind(..)。

typeof Function.prototype; // "function"
Function.prototype(); // 空函数!

RegExp.prototype.toString(); // "/(?:)/"——空正则表达式
"abc".match( RegExp.prototype ); // [""]
1
2
3
4
5
Array.isArray( Array.prototype ); // true
Array.prototype.push( 1, 2, 3 ); // 3
Array.prototype; // [1,2,3]
// 需要将Array.prototype设置回空,否则会导致问题!
Array.prototype.length = 0;
1
2
3
4
5

Function.prototype 是一个函数

RegExp.prototype 是一个正则表达式

Array.prototype 是一个数组

Function.prototype 是一个空函数,RegExp.prototype 是一个“空”的正则表达式

Array.prototype 是一个空数组

对未赋值的变量来说,它们是很好的默认值。

# 3.5 小结

JavaScript 为基本数据类型值提供了封装对象,称为原生函数(如 String、Number、Boolean等)。它们为基本数据类型值提供了该子类型所特有的方法和属性(如:String#trim() 和Array#concat(..))。

上次更新: 2022/8/22 下午3:40:53