內(nèi)置對象

2018-07-10 09:55 更新

Table of Contents generated with DocToc

內(nèi)置對象

通常情況下只有對象才存在方法,但 JavaScript 不同它具有12種內(nèi)置對象。內(nèi)置對象又分為兩類,普通對象(屬性和方法)與構造器對象(可用于實例化普通對象,它還包含原型對象屬性和方法,及實例對象屬性和方法)。

JavaScript 對象原型鏈的簡要說明

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);
p.move(2,2);

__proto__ 稱之為原型鏈,有如下特點:

  1. __proto__ 為對象內(nèi)部的隱藏屬性
  2. __proto__ 為實例化該對象的構造器的 prototype 對象的引用,因此可以直接方法 prototype 的所有屬性和方法
  3. 除了 Object 每個對象都有一個 __proto__ 屬性且逐級增長形成一個鏈,原型鏈頂端是一個 Object對象。
  4. 在調用屬性或方法時,引擎會查找自身的屬性如果沒有則會繼續(xù)沿著原型鏈逐級向上查找,直到找到該方法并調用。
  5. __proto__ 跟瀏覽器引擎實現(xiàn)相關,不同的引擎中名字和實現(xiàn)不盡相同(chrome、firefox中名稱是 __proto__ ,并且可以被訪問到,IE中無法訪問)?;诖a兼容性、可讀性等方面的考慮,不建議開發(fā)者顯式訪問 __proto__ 屬性或通過 __proto__更改原型鏈上的屬性和方法,可以通過更改構造器prototype 對象來更改對象的 __proto__ 屬性。

構造器對象與普通對象的區(qū)別

  1. 構造器對象原型鏈中的 __proto__ 是一個 Function.prototype 對象的引用,因此可以調用 Function.prototype的屬性及方法
  2. 構造器對象本身有一個 prototype 屬性,用該構造器實例化對象時該 prototype 會被實例對象的 __proto__ 所引用
  3. 構造器對象本身是一個 function 對象,因此也會有自身屬性

標準內(nèi)置對象

構造器對象

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

其他對象

  • Math
  • JSON
  • 全局對象

內(nèi)置對象,其實也叫內(nèi)置構造器,它們可以通過 new 的方式創(chuàng)建一個新的實例對象。內(nèi)置對象所屬的類型就叫內(nèi)置對象類型。其聲明方式如下:

var i = new String("str");          // String Object
var h = new Number(1);              // Number Object
var g = new Boolean(true);          // Boolean 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,內(nèi)置對象類型中也有Boolean StringNumber Object,但它們其實是通過不同的聲明方式來進行區(qū)別的。標準類型通過直接賦值,而對象類型則是通過構造器實現(xiàn)初始化。

Object

構造器的原型對象在對象實例化時將會被添加到實例對象的原型鏈當中。 __proto__ 為原型鏈屬性,編碼時不可被顯像調用。但是實例化對象可以調用原型鏈上的方法。

用 String/Number 等構造器創(chuàng)建的對象原型鏈頂端對象始終是一個Object對象,因此這些對象可以調用Object的原型對象屬性和方法。所以 String/Number 等構造器是 Object 的子類。

更多關于 Object 的內(nèi)容可以在這里找到。

構造器說明

  • Object 是屬性和方法的集合
  • String/Number/Boolean/Array/Date/Error 構造器均為 Object 的子類并集成 Object 原型對象的屬性及方法。

實例化方法

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

屬性及方法

  • prototype
  • create
  • keys
  • ...

**原型對象屬性及其方法

  • constructor
  • toString
  • valueOf
  • hasOwnProperty
  • ...

實例對象屬性及方法

Object.create

功能:基于原型對象創(chuàng)造新對象

// Object.create(prototype[, propertiesObject])
var prototype = {name: 'X', age: 13};
var obj = Object.create(proto);

Object.prototype.toString

功能:獲取方法調用者的標準類型

// 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

Boolean

構造器說明:值為 true 與 false

屬性及方法

  • prototype

**原型對象屬性及其方法

  • constructor, toString, valueOf

String

構造器說明:單雙引號內(nèi)的字符串

實例化方法

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

屬性及方法

  • prototype
  • fromCharCode(轉換 ASCII 代碼為字符)

原型對象屬性及其方法

  • constructor
  • indexOf
  • replace
  • slice
  • split
  • charCodeAt
  • toLowerCase
  • ...

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

功能:按分隔符將分隔符分成字符串數(shù)組

// 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+/); // ["", " ", " ", " ", ""]

Number

構造器說明:整型直接量,八進制直接量(0-),十六進制直接量(0x-),浮點型直接量

實例化方法

10
1.2e5
var count = 0x10;
var pi = new Number(3.1415);

屬性及方法

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

原型對象屬性及其方法

  • constructor
  • toFixed
  • toExponential
  • ...

Number.prototype.toFixed

功能:四舍五入至指定小數(shù)位

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

Array

構造器說明:定義數(shù)組對象

實例化方法

var a0 = [1, 'abc', true, function(){}];
var a1 = new Array();
var a2 = new Array(1, 'abc', true);

屬性及方法

  • prototype
  • isArray

原型對象屬性及其方法

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

Array.prototype.splice

功能:從數(shù)組中刪除或添加元素,返回被刪除的元素列表(作用域原有數(shù)組)

// arrayObject.splice(start, deleteCount[, item1[, item2[, ...]]])
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

功能:遍歷元素組并調用回調函數(shù)

// arrayObject.forEach(callback[, thisArg])
// 回調函數(shù)
// function callback(value, index, arrayObject) {...}
// value - 當前值 index - 當前索引 arrayObject - 數(shù)組本身
function logArray(value, index, arrayObject) {
  console.log(value);
  console.log(value === array[index]);
}
[2, 5, 6, 9].forEach(logArray);

Function

構造器說明:定義函數(shù)或新增對象構造器

實例化方法

// 對象實例化
var f0 = new Function('i', 'j', 'return (i + j)');
// 函數(shù)關鍵字語句
function f1(i, j){return i + j;}
// 函數(shù)表達式
var f3 = function(i, j){return i + j;};

屬性及方法

  • prototype

原型對象屬性及其方法

  • constructor
  • apply
  • call
  • bind

實例對象屬性和方法

  • length
  • prototype
  • arguments
  • caller

自定義對象構造器

下面的代碼聲明一個 Point 增加了一個move方法,最后創(chuàng)建了一個 Point 的實例對象。

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);

Function.prototype.apply

功能:通過參數(shù)指定調用者和函數(shù)參數(shù)并執(zhí)行該函數(shù)

// 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

功能:通過參數(shù)指定函數(shù)調用者和函數(shù)參數(shù)并返回該函數(shù)的引用

// 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}

// 之間使用 circleMoveRef() 效果等同于 apply()
circleMoveRef();

子類構造器

function Circle(x, y, r) {
  Point.apply(this, [x, y]);
  this.radius = r;
}
Circle.prototype = Object.create(Point.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.area = function(){
  return Math.PI * this.radius * this.radius;
}

var c = new Circle(1, 2, 3);
c.move(2, 2);
c.area();

函數(shù)調用

  • ()
  • apply
  • call

函數(shù)參數(shù)

  • 形參個數(shù)不一定等于實參個數(shù)
  • 值專遞
  • 通過參數(shù)類型檢查實現(xiàn)函數(shù)重載
arguments

arguments 的常用屬性

  • length 實參個數(shù)
  • 0...arguments.length-1 實參屬性名稱(key)
  • callee 函數(shù)本身
function max(a, b) {
  if (max.length === arguments.length) {
    return a>b?a:b;
  } else {
    var _max = arguments[0];
    for(var i = 0; i < arguments.length; i++) {
      if (_max < arguments[i]) {
        _max = arguments[i];
      }
    }
    return _max;
  }
}
值專遞

函數(shù)參數(shù)的值專遞是參數(shù)復制都是棧內(nèi)存中的復制。

// 原始類型
function plusplus(num) {
  return num++;
}
var count = 0;
var result = plusplus(count); // result = 1; count = 0;

// 引用類型
function setName(obj) {
  obj.name = 'obama';
}
var president = {name: 'bush'};
setName(president); // {name: 'obama'};
函數(shù)重載

以 Require.JS 中的 define() 為例:

define(function(){
  var add = function(x, y) {
    return x + y;
  };
  return {
    add: add
  };
})

define(['lib'], function(){
  var add = function(x, y) {
    return x + y;
  };
  return {
    add: add
  };
})

define('math', ['lib'], function(){
  var add = function(x, y) {
    return x + y;
  };
  return {
    add: add
  };
})

// define 的實現(xiàn)代碼
/**
 * The function that handles definitions of modules. Differs from
 * require() in that a string for the module should be the first argument,
 * and the function to execute after dependencies are loaded should
 * return a value to define the module corresponding to the first argument's
 * name.
 */
define = function (name, deps, callback) {
    var node, context;

    //Allow for anonymous modules
    if (typeof name !== 'string') {
        //Adjust args appropriately
        callback = deps;
        deps = name;
        name = null;
    }

    //This module may not have dependencies
    if (!isArray(deps)) {
        callback = deps;
        deps = null;
    }

    // 省略以下代碼
    // ...
};

RegExp

構造器說明:用于定義正則表達式,一個 RegExp 對象包含一個正則表達式和關聯(lián)的標志

定義方法

  • /pattern/flags
  • new RegExp(pattern[, flags]);

屬性及方法

  • prototype

原型對象屬性及其方法

  • constructor
  • test
  • exec
  • ...

RegExp.prototype.test

功能:使用正則表達式對字符串進行測試,并返回測試結果

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

Date

構造器說明:用于定義日期對象

定義方法

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

屬性及方法

  • prototype
  • parse
  • now
  • ...

原型對象屬性及其方法

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

標準內(nèi)置對象

Math

對象說明:擁有屬性和方法的單一對象主要用于數(shù)字計算

對象屬性

  • E
  • PI
  • SQRT2
  • ...

對象方法

  • 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

相似方法:ceil,round

Math.random

功能:返回 0~1 之間的浮點數(shù)

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

JSON

對象說明:用于存儲和交換文本信息

對象方法

  • 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'}

全局對象

全局對象定義了一系列的屬性和方法在編程過程中可以被之間調用。

屬性:NaN,Infinity,undefined

方法:

  • parseInt
  • parseFloat
  • isNaN
  • isFinite
  • eval

處理 URI 方法:

  • encodedURIComponent
  • decodeURIComponent
  • encodedURI
  • decodeURI

構造器屬性:

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

對象屬性:

  • Math
  • JSON
NaA

非數(shù)字值:表示錯誤或無意義的運算結果,NaN 參與運算仍會返回 NaA,且 NaN 不等于任何值,包括它本身??梢允褂?nbsp;isNaN() 判斷運算結果的類型是否為 NaN。

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

功能:轉換字符串成數(shù)字

// parseInt(string[, radix])
// radix - 為進制數(shù)
parseInt('010'); // 10
parseInt('010', 8) // 8
parseInt('010', 16) // 16

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

功能:計算字符串并執(zhí)行其中的 JavaScript 代碼(會帶來安全性和代碼邏輯問題,通常不建議使用)

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

功能:將 URI 參數(shù)中的特殊字符,中文等作為 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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號