JavaScript--创建对象和生成原型链的方法

来源:互联网 发布:中国海洋大学网络登录 编辑:程序博客网 时间:2024/05/18 11:47

最近在看MDN上的文档,总结一下

普通语法创建对象

var o = {a: 1};// 原型链如下:// 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.vertices = [];  this.edges = [];}Graph.prototype = {  addVertex: function(v){    this.vertices.push(v);  }};var g = new Graph();// g是生成的对象,他的自身属性有'vertices''edges'.// 在g被实例化时,g.[[Prototype]]指向了Graph.prototype.

使用 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。这些新的关键字包括 class, constructor, static, extends, 和 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);

性能

在原型链上查找属性比较耗时,对性能有副作用,这在性能要求苛刻的情况下很重要。另外,试图访问不存在的属性时会遍历整个原型链

遍历对象的属性时,原型链上的每个可枚举属性都会被枚举出来。

检测对象的属性是定义在自身上还是在原型链上,有必要使用 hasOwnProperty 方法,所有继承自 Object.proptotype 的对象都包含这个方法。

hasOwnProperty 是 JavaScript 中唯一一个只涉及对象自身属性而不会遍历原型链的方法。

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

0 0
原创粉丝点击