创建对象的几种方式:
字面量创建
var o ={a:1,b:2};原型链如下:o ---> Object.prototype --->null继承的属性比如:hasOwnPropertyvar a = ["i", "like", "you"];原型链如下:a ---> Array.prototype ---> Object.prototype ---> null继承的属性比如:indexOf,forEachvar 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 ---> nullvar b = Object.create(a);//b ---> a ---> Object.prototype --->nullvar c = Object.create(b);//c ---> b ---> a ---> Object.prototype --->nullvar d = Object.create(null);//d ---> nullconsole.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);