创建对象的几种方式:

字面量创建

var o ={a:1,b:2};
原型链如下:
o ---> Object.prototype --->null
继承的属性比如:hasOwnProperty

var a = ["i", "like", "you"];
原型链如下:
a ---> Array.prototype ---> Object.prototype ---> null
继承的属性比如:indexOf,forEach

var f = function(){return 2;}
原型链如下:
f ---> Function.prototype ---> Object.prototype ---> null
继承的属性比如:call,bind,apply

使用构造器创建对象

构造器就是一个普通的函数
function Graph(){
    this.vertexes = [];
    this.edges = [];
}

Graph.prototype = {
    addVertex: function(v){
        this.vertexes.push(v);
    }
};

var g = new Graph();
// g是生成的对象,它的自身属性有'vertexes','edges',
// 在g被实例化时,g.[[prototype]]指向了Graph.prototype

使用Object.create创建对象

var a = {a:1};
// a ---> Object.prototype ---> null

var b = Object.create(a);
//b ---> a ---> Object.prototype --->null

var c = Object.create(b);
//c ---> b ---> a ---> Object.prototype --->null

var d = Object.create(null);
//d ---> null
console.log(d.hasOwnProperty); // undefined,因为d没有继承Object.prototype

使用class关键字

‘use strict’

class Polygon {
    constructor(height,width){
        this.height = height;
        this.width = width;
    }
}

class Square extends Polygon {
    constructor(sideLength){
        super(sideLength, sideLength);
    }
    get area() {
        return this.height * this.width;
    }
    set sideLength(newLength) {
        this.height = newLength;
        this.wdith = newLength;
    }
}

var square = new Square(2);

bottle_
259 声望22 粉丝

好好学习,好好生活,好好工作