原型

  • 每个对象都有原型,原型里存着对象的共有属性和方法
  • obj.__proto__存着obj的原型的地址,这个对象里有 toString/constructor/valueOf 等属性
  • 对象的原型也是对象,所以对象的原型也有原型
  • obj = {}的原型为Object.prototype即为所有对象的原型,这个原型的原型是null
  • 对象.__proto__ === 其构造函数的prototype:构造函数使用自己的原型作为原型构造对象
  • __ptoto__与 prototype 的区别:__ptoto__是对象的属性,prototype 是 构造函数的属性

    构造函数

  • 构造函数就是 制造对象工厂

  • 构造函数名的首字母要大写
  • 通过对象的 constructor 属性查看其构造函数
  • 系统自带构造函数 :Object(), Array() …
  • 自定义构造函数:

    1. // new X() 自动做了四件事:
    2. // 1. 创建空对象
    3. // 2. 为这个空对象关联原型,原型地址为 X.prototype
    4. // 3. 使用 this 指向这个空对象,运行构造函数
    5. // 4. 自动 return this
    6. function Zhuzhu(age) {
    7. /* var this = {
    8. __ptoto__: Zhuzhu.prototype;
    9. };
    10. var this = Object.create(Zhuzhu.prototype); 以Zhuzhu.prototy为原型创建对象
    11. */
    12. this.age = age;
    13. this.weight = 80kg;
    14. // return this;
    15. }
    16. Zhuzhu.prototype.sleep = function() {
    17. console.log('Zhuzhu is sleeping!');
    18. };
    19. Zhuzhu.prototype.eat = function() {
    20. console.log('Zhuzhu is eating!');
    21. }
    22. Zhuzhu1 = new Zhuzhu(18);
    23. Zhuzhu2 = new Zhuzhu(2);
  • 构造函数 X 的作用:

    • 构造函数 X 本身负责给对象本身添加属性
    • X.prototype 对象负责保存构造函数 X对象的公用属性

prototype.png
zhuzhu1.__proto__ === Zhuzhu.prototype

原型链

proLink.png

  • Object.prototype === zhuzhu1.__proto__.__proto__ === Zhuzhu.prototype.__proto__
  • zhuzhu1.toString === zhuzhu1.__proto__.__proto__.toString

Object 与 Function

  • Object 与 Function 都是函数
  • 普通对象是 Object 创造的,Object.prototype 是所有对象的直接或间接原型
  • 任何函数都是由 Function 创造的
  • Function 创造了 Function
    1. Function.prototype === fn.__proto__ // true
    2. ({}).constructor === Object // true
    3. Object.constructor === Function // true

    Object-Fun.png

    Class 语法

    写法有点像 java
    1. class Zhuzhu{ //class首字母小写
    2. static lovely = true;
    3. constructor(age) {
    4. this.age = age;
    5. }
    6. age18() {
    7. console.log('zhuzhu is always 18');
    8. }
    9. }
    10. let zhuzhu = new Zhuzhu(18);
    11. zhuzhu.age18;