首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《JavaScript程序设计》第2课:JS类型系统

《JavaScript程序设计》第2课:JS类型系统

作者头像
陈树义
发布2018-04-13 16:22:04
7870
发布2018-04-13 16:22:04
举报
文章被收录于专栏:陈树义陈树义

JS类型系统可以分为标准类型和对象类型,进一步标准类型又可以分为原始类型和引用类型,而对象类型又可以分为内置对象类型、普通对象类型、自定义对象类型。

1. 标准类型

标准类型共包括了6个分别是:undefined Null Boolean Number String Object,其中undefined Null Boolean Number String是原始类型,而Object是引用类型。其声明方式如下:

var a;    //undefined
var b = document.getElementById("no_exist_element"); //null
var c = true;    //Boolean
var d = 1;    //Number
var e = "str";     //String
var f = {name : "Tom"};    //Object

原始类型和引用类型的区别:

原始类型储存在栈(Stack)中储存变量的值,而引用类型在栈中保存的是所引用内容储存在堆(Heap)中的值。类似于指针的概念,引用类型并非储存变量真实数值而是地址,所以对已引用类型的复制其实只是复制了相同的地址而非实际的变量值。

1.1 Undefined 

值:undefined

出现场景:

- 已声明未赋值的变量 var obj;

- 获取对象不存在的属性 var obj = {x: 0}; obj.y;

- 无返回值函数的执行结果 function f(){}; var obj = f();

- 函数参数没有传入 function f(i){console.log(i)}; f();

- void(expression)

1.2 Null

值:null

出现场景:

- 获取不存在的对象 document.getElementById('not-exist-element')

1.3 Boolean

值:true false

出现场景:

- 条件语句导致的系统执行的隐式类型转换 if(隐式转换){}

if(document.getElementById('not-exist-element')){
    //
}else{
    //执行这里的代码
}

上面的if(document.getElementById('not-exist-element'))等于if(Boolean(document.getElementById('not-exist-element')))

- 字面量或变量定义 var bool = true;

1.4 String

值:字符串

出现场景:

直接声明 var str = 'Hello, world!';

1.5 Number

值:整型直接量,八进制直接量(0-),十六进制直接量(0x-),浮点型直接量

出现场景:

- 1026

- 1.2e5

- 010

- 0x10

- 3.14

1.6 Object

值:属性集合

出现场景:

- var obj = {name: 'Xinyang'};

1.7 变量转换表

Value

Boolean

Number

String

undefined

false

NaN

"undefined"

null

false

0

"null"

true

true

1

"true"

false

false

0

"false"

''

false

0

''

'123'

true

123

'123'

'1a'

true

NaN

'1a'

0

false

0

"0"

1

true

1

"1"

Infinity

true

Infinity

"Infinity"

NaN

false

NaN

'NaN'

{}

true

NaN

"[object Object]"

2.对象类型

2.1 内置对象类型

内置对象,其实也叫内置构造器,它们可以通过new方式创建一个新的对象。内置对象所属的类型就叫内置对象类型。

内置对象一共有9个,分别是:Boolean String Number Object Array Date Error Function RegExp。其声明方式如下:

var g = new Boolean(true);    //Boolean Object
var h = new Number(1);    //Number Object
var i = new String("str");    //String Object
var j = new Object({name : "Tom"}); //Object Object 
var k = new Array([1, 2, 3, 4]);    //Array Object
var l = new Date();    //Date Object
var m = new Error();
var n = new Function();    
var o = new RegExp("\\d");

要注意,虽然标准类型中有Boolean String Number Object,内置对象类型中也有Boolean String Number Object,但它们其实是通过不同的声明方式来进行区别的。标准类型通过直接赋值,而对象类型则是通过构造器实现初始化。

var stdType = "hello";  //标准类型
var objType = new String("hello");  //对象类型

上面两种声明方式,stdType是标准类型,而objType是对象类型。

2.1.1 Object

(1)实例化方法

var obj0 = new Object({name: 'X', age: 13});
// 常用方法
var obj1 = {name: 'Q', age: 14};

(2)属性及方法(相当于类的静态方法)

prototype、create、keys...

(3)原型对象属性及其方法(相当于父类的方法)

constructor、toString、valueOf、hasOwnProperty...

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

(5)举例

Object.create

功能:基于原型对象创造新对象

// objectInstance.toString()
var obj = {};
obj.toString(); // Object
Object.prototype.hasOwnProperty

功能:判断一个属性是否是一个对象的自身属性

// objectInstance.hasOwnProperty("propertyName")
var obj = Object.create({a: 1, b: 2});
obj.c = 3;
obj.hasOwnProperty('a'); // false
obj.hasOwnProperty('c'); // true

2.1.2 Boolean 

(1)实例化方法

var flag = new Boolean("true");

(2)属性及方法(相当于类的静态方法)

prototype

(3)原型对象属性及其方法(相当于父类的方法)

constructor, toString, valueOf...

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

2.1.3 String

(1)实例化方法

'Hello, world!'
var str0 = 'Xinyang';
var str1 = new String('Xinyang');

(2)属性及方法(相当于类的静态方法)

prototype、fromCharCode(转换 ASCII 代码为字符)

(3)原型对象属性及其方法(相当于父类的方法)

constructor、indexOf、replace、slice、split、charCodeAt、toLowerCase

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

(5)例子

String.prototype.indexOf

功能:获取子字符串在字符串中的索引

// stringObject.indexOf(searchValue, fromIndex)
var str = "I am X. From China!";
var index = str.indexOf('a'); // 2
str.indexOf('a', index + 1); // 16
str.indexOf('Stupid'); // -1 字符串不存在
String.prototype.replace

功能:查找字符串替换成目标文字

// stringObject.replace(regexp/substr, replacement)
var str = "apple is bad";
str = str.replace('bad', 'awesome');
String.prototype.split

功能:按分隔符将分隔符分成字符串数组

// stringObject.split(separator, arrayLength)
var str = '1 2 3 4';
str.split(' '); // ['1', '2', '3', '4'];
str.split(' ', 3); // ['1', '2', '3'];
str.split(/\d+/); // ["", " ", " ", " ", ""]

2.1.4 Number

(1)实例化方法

var num = new Number("10");

(2)属性及方法(相当于类的静态方法)

  • prototype
  • MAX_VALUE
  • MIN_VALUE
  • NaN
  • NEGATIVE_INFINITY
  • POSITIVE_INFINITY

(3)原型对象属性及其方法(相当于父类的方法)

  • constructor
  • toFixed
  • toExponential
  • ...

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

(5)例子

Number.prototype.toFixed

功能:四舍五入至指定小数位

// numberObject.toFixed(num)
var num0 = 3.14;
num0.toFixed(1); // 3.1
var num1 = 3.35;
num1.toFixed(1); // 3.4

2.1.5 Array

(1)实例化方法

var a2 = new Array(1, 'abc', true);

(2)属性及方法(相当于类的静态方法)

  • prototype
  • isArray

(3)原型对象属性及其方法(相当于父类的方法)

  • constructor
  • splice
  • forEach
  • find
  • concat
  • pop
  • push
  • reverse
  • shift
  • slice

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

  • length

(5)例子

Array.prototype.splice

功能:从数组中删除或添加元素,返回被删除的元素列表(作用于原有数组)

// arrayObject.splice(start, deleteCount[, addedItem1[, addedItem2[, ...]]])
var arr = ['1', '2', 'a', 'b', '6'];
var ret = arr.splice(2, 2, '3', '4', '5'); // ['a', 'b']
arr; // ['1', '2', '3', '4', 5', '6']
Array.prototype.forEach

功能:遍历元素组并调用回调函数

// arrayObject.forEach(callback[, thisArg])
// 回调函数
// function callback(value, index, arrayObject) {...}
// value - 当前值 index - 当前索引 arrayObject - 数组本身
function logArray(value, index, arrayObject) {
  console.log(value);
  console.log(value === array[index]);
}
[2, 5,  , 9].forEach(logArray);

2.1.6 Function

(1)实例化方法

// 对象实例化
var f0 = new Function('i', 'j', 'return (i + j)');
// 函数关键字语句
function f1(i, j){return i + j;}
// 函数表达式
var f3 = function(i, j){return i + j;};

(2)属性及方法(相当于类的静态方法)

  • prototype

(3)原型对象属性及其方法(相当于父类的方法)

  • constructor
  • apply
  • call
  • bind

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

  • length 实参个数
  • prototype
  • arguments
  • caller 调用者

(5)例子

Function.prototype.apply

功能:通过参数指定调用者和函数参数并执行该函数

// functionObj.apply(thisArg[, argsArray])
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 1);
var circle = {x: 1, y: 1, r: 1};
p.move.apply(circle, [2, 1]); // {x: 3, y: 2, r: 1}
Function.prototype.bind

功能:通过参数指定函数调用者和函数参数并返回该函数的引用

// functionObj.bind(thisArg[, arg1[, arg2[, ...]]])
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 1);
var circle = {x: 1, y: 1, r: 1};
var circleMoveRef = p.move.bind(circle, 2, 1);
setTimeout(circleMoveRef, 1000); // {x: 3, y: 2, r: 1}

//去掉setTimeout(...)语句而直接使用 circleMoveRef() 效果等同于 apply()
//circleMoveRef();

2.1.7 RegExp

(1)实例化方法

var regExp = new RegExp(/\d+/i);

(2)属性及方法(相当于类的静态方法)

  • prototype

(3)原型对象属性及其方法(相当于父类的方法)

  • constructor
  • test
  • exec
  • ...

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

(5)例子

RegExp.prototype.test

功能:使用正则表达式对字符串进行测试,并返回测试结果

// regexObj.text(str)
var reg = /^abc/i;
reg.test('Abc123'); // true
reg.test('1Abc1234'); // false

2.1.8 Date

(1)实例化方法

var date0 = new Date();
var date1 = new Date(2014, 3, 1, 7, 1, 1, 100);

(2)属性及方法(相当于类的静态方法)

  • prototype
  • parse
  • now
  • ...

(3)原型对象属性及其方法(相当于父类的方法)

  • constructor
  • Date
  • getDate
  • getHours
  • setDate
  • setHours
  • ...

(4)实例对象属性及方法(相当于实例化后才能调用的方法)

2.2 普通对象类型

普通对象类型包括Math、JSON、全局对象三种,普通对象类型的特点就是其直接可以通过Math.method方式调用,类似于工具类一样,可以直接通过类调用静态方法。如:Math.random()返回一个0-1之间的随机数,JSON.parse(jsonStr)解析JSON字符串为JSON对象……

2.2.1 Math

(1)对象说明

拥有属性和方法的单一对象主要用于数字计算

(2)对象属性

  • E
  • PI
  • SQRT2
  • ...

(3)对象方法

  • floor
  • random
  • abs
  • max
  • cos
  • ceil
Math.floor

功能:向下取整

// Math.floor(num)
Math.floor(0.97); // 0
Math.floor(5.1); // 5
Math.floor(-5.1); //6

相似方法:ceilround

Math.random

功能:返回 0~1 之间的浮点数

// Math.random()
Math.random(); // 0.14523562323461

2.2.2 JSON

(1)对象说明

用于存储和交换文本信息

(2)对象方法

  • parse
  • stringify
JSON.stringify

功能:将 JSON 对象转换为字符转

// JSON.stringify(value[, replacer[, space]])
var json = {'name': 'X'};
JSON.stringify(json); // "{"name":"X"}"
JSON.parse

功能:将 JSON 字符转转换为对象

// JSON.parse(text[, reviver])
var jsonStr = '{"name":"X"}';
JSON.parse(jsonStr); // {name: 'X'}

2.2.3 全局对象

全局对象定义了一系列的属性和方法在编程过程中可以被之间调用。

(1)属性

NaN,Infinity,undefined

(2)方法

  • parseInt
  • parseFloat
  • isNaN
  • isFinite
  • eval

处理 URI 方法:

  • encodedURIComponent
  • decodeURIComponent
  • encodedURI
  • decodeURI

构造器属性:

  • Boolean
  • String
  • Number
  • Object
  • Function
  • Array
  • Date
  • Error
  • ...

对象属性:

  • Math
  • JSON
NaN

非数字值:表示错误或无意义的运算结果,NaN 参与运算仍会返回 NaA,且 NaN 不等于任何值,包括它本身。可以使用isNaN() 判断运算结果的类型是否为 NaN。

isNaN(NaN); // true
isNaN(4 - '2a'); // flase;
parseInt

功能:转换字符串成数字

// parseInt(string[, radix])
// radix - 为进制数
parseInt('010'); // 10
parseInt('010', 8) // 8
parseInt('010', 15) // 16

parseInt('0x1f'); // 31
parseInt('0x1f', 16); // 31
parseInt('1f'); // 1
parseInt('1f', 16); // 32
eval

功能:计算字符串并执行其中的 JavaScript 代码(会带来安全性和代码逻辑问题,通常不建议使用)

// eval(string)
var res = '{"error": "0", "msg": "OK"};
var obj;
if (!JSON) {
  obj = eval('(' + res + ')');
} else {
  obj = JSON.parse(res);
}
encodedURIComponent

功能:将 URI 参数中的特殊字符,中文等作为 URI 的一部分进行编码

var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var res = encodeURIComponent(uri);

// 结果
// http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

2.3 自定义对象类型

自定义对象类型就是自己定义的对象,可以理解成Java中的类。

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 2);

上面代码声明一个Point对象,并为Point对象增加了一个move方法,最后创建了一个Point对象。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-06-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 标准类型
  • 2.对象类型
    • Object.create
      • Object.prototype.hasOwnProperty
        • String.prototype.indexOf
          • String.prototype.replace
            • String.prototype.split
              • Number.prototype.toFixed
                • Array.prototype.splice
                  • Array.prototype.forEach
                    • Function.prototype.apply
                      • Function.prototype.bind
                        • RegExp.prototype.test
                          • 2.2 普通对象类型
                            • 2.3 自定义对象类型
                            领券
                            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档