重学前端-学习笔记-JavaScript对象-类

说明

重学前端是程劭非(winter)在极客时间开的一个专栏,在此主要整理个人学习笔记。若有侵权,请联系我,谢谢。前端

js的原型

  • 若是全部对象都有私有字段[[prototype]],就是对象的原型
  • 读一个属性,在该对象上找不到,就会去它的原型上查找,直到原型为空或者找到为止

js提供内置函数,来访问和操纵原型bash

  • Object.create:根据指定的原型来建立新对象,原型能够是null
  • Object.getPropertyOf:获取对象的原型
  • Object.setPropertyOf:设置对象的原型
var cat = {
    say(){
        console.log("meow~");
    },
    jump(){
        console.log("jump");
    }
}

var tiger = Object.create(cat,  {
    say:{
        writable:true,
        configurable:true,
        enumerable:true,
        value:function(){
            console.log("roar!");
        }
    }
})


var anotherCat = Object.create(cat);

anotherCat.say();

var anotherTiger = Object.create(tiger);

anotherTiger.say();

复制代码

早期版本中的类与原型

(待补充)函数

new操做

new运算一个构造器和一组参数,实际作了这三件事学习

  • 以构造器的prototype属性为原型,建立新对象
  • 讲this和参数传给构造器,执行
  • 若是构造器返回的是对象,则返回,如无,就返回第一步建立的对象

new操做让函数对象在语法上跟类类似,可是,它提供了两种方式,一种是在构造器添加属性,一种是经过构造器的prototype属性添加属性ui

// 经过构造器
function c1(){
    this.p1 = 1;
    this.p2 = function(){
        console.log(this.p1);
    }
} 
var o1 = new c1;
o1.p2();


// 经过构造器的原型
function c2(){
}
c2.prototype.p1 = 1;
c2.prototype.p2 = function(){
    console.log(this.p1);
}

var o2 = new c2;
o2.p2();

复制代码

用new来实现一个Object。create的不完整polyfillthis

Object.create = function(prototype){
    var cls = function(){}
    cls.prototype = prototype;
    return new cls;
}
复制代码

这段代码建立了一个空函数做为类,并把传入的原型挂在了它的prototype,最后建立了一个它的实例,根据 new 的的行为,这将产生一个以传入的第一个参数为原型的对象。spa

ES6中的类

类的基本写法prototype

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

复制代码

经过get/set来建立getter,经过括号和大括号来建立方法,数据型成员写在构造器里。设计

类提供了继承能力code

class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }

  speak() {
    console.log(this.name + ' barks.');
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

复制代码

比起早期的原型模拟方式,使用 extends 关键字自动设置了 constructor,而且会自动调用父类的构造函数,这是一种更少坑的设计。

相关文章
相关标签/搜索