★06.对象

2017-07-03  本文已影响0人  iDragonfly

简介

三种创建方式

对象直接量

var empty = {};

var abc = {
    abcdef: "str",          // 属性名可以是一个标识符
    "abcdef": 123,          // 属性名可以是一个字符串
    "abc def": 123,         // 有空格的属性名必须是一个字符串
    'abc-def': true         // 有连字符的属性名必须是一个字符串
};

new

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

var p = new Point(1, 1);

// 不需要传入任何参数给构造函数时,可以省略括号
new Object
new Date

Object.create()

var o1 = Object.create({x : 1, y : 2});     // 创建了o1对象,o1继承了属性x和y
var o2 = Object.create(null);               // 创建了o2对象,o2不继承任何属性和方法
var o3 = Object.create(Object.prototype);   // 创建了o3对象,o3和{}和new Object()一样
function inherit(p) {
    if (p === null) throw TypeError();
    if (Object.create) return Object.create(p);

    var t = typeof p;

    if (t !== "object" && t !== "function") throw TypeError();
    function f() {
    }

    f.prototype = p;
    return new f();
}
var o = {x : "don't change this value"};
library_function(inherit(o));           // 通过继承时拷贝继承的属性,来避免意外修改了o

序列化对象

继承于Object的方法

toString()方法

toLocaleString()方法

toJSON()方法

valueOf()方法

对象的三个属性

原型属性

类属性

简述

简单示例

function classof(o) {
    if (o === null) return "Null";
    if (o === undefined) return "undefined";
    return Object.prototype.toString.call(o).slice(8, -1);
}

classof(null)               // "Null"
classof(1)                  // "Number"
classof("")                 // "String"
classof(false)              // "Boolean"
classof({})                 // "Object"
classof([])                 // "Array"
classof(/./)                // "RegExp"
classof(new Date())         // "Date"
classof(window)             // "Window" (a client-side host object)
function f() { };
classof(new f());           // "Object"

可拓展性

简述

上一篇下一篇

猜你喜欢

热点阅读