使用不同的方法来创建对象和生成原型链

来源:互联网 发布:办公软件激活 编辑:程序博客网 时间:2024/05/16 16:00

使用不同的方法来创建对象和生成原型链

使用普通语法创建对象

var o = {a: 1};// o这个对象继承了Object.prototype上面的所有属性// 所以可以这样使用 o.hasOwnProperty('a').// hasOwnProperty 是Object.prototype的自身属性。// Object.prototype的原型为null。// 原型链如下:// o ---> Object.prototype ---> nullvar a = ["yo", "whadup", "?"];// 数组都继承于Array.prototype // (indexOf, forEach等方法都是从它继承而来).// 原型链如下:// a ---> Array.prototype ---> Object.prototype ---> nullfunction f(){  return 2;}// 函数都继承于Function.prototype// (call, bind等方法都是从它继承而来):// f ---> Function.prototype ---> Object.prototype ---> null

使用构造器创建对象

在 JavaScript 中,构造器其实就是一个普通的函数。当使用 new 操作符 来作用这个函数时,它就可以被称为构造方法(构造函数)。

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 创建对象

ECMAScript 5 中引入了一个新方法:Object.create()。可以调用这个方法来创建一个新对象。新对象的原型就是调用 create 方法时传入的第一个参数:

var a = {a: 1}; // a ---> Object.prototype ---> nullvar b = Object.create(a);// b ---> a ---> Object.prototype ---> nullconsole.log(b.a); // 1 (继承而来)var c = Object.create(b);// c ---> b ---> a ---> Object.prototype ---> nullvar d = Object.create(null);// d ---> nullconsole.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype

使用 class 关键字

ECMAScript6 引入了一套新的关键字用来实现 class。使用基于类语言的开发人员会对这些结构感到熟悉,但它们是不一样的。 JavaScript 仍然是基于原型的。这些新的关键字包括 classconstructor,staticextends, 和 super.

"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.width = newLength;  }}var square = new Square(2);
1 0
原创粉丝点击