zoukankan      html  css  js  c++  java
  • [Javascript] Understanding the .constructor property on JavaScript Objects

    Constructor functions hold an interesting purpose in JavaScript. Unlike in classical languages, they do not always mean created by. In this lesson we’ll use the new keyword to make a constructor call and work with the .constructor property.

    When we define a function:

    function Foo(){
        //.
    }

    It has one prototype prop defined which is constructor. And it points to the Foo function itself.

    console.log(Foo.prototype.constructor === Foo) // true

    And if we have an instance created by new keyword:

    const f= new Foo();

    Then:

    console.log(f.constructor === Foo) // true

    So which mean:

    f.constructor === Foo.prototype.constructor

    This prototype chain can be broken when we reassgin the Foo.prototype = {}:

    Foo.prototype = {}; // now we reassign to an empty object.
    console.log(Foo.prototype.constructor === Foo);  // false
    console.log(f.constructor === Foo); //true
    console.log(f.constructor === Foo.prototype.constructor); // false

    We can use Object.defineProperty to reassign the constructor to the Foo.prototype:

    Foo.prototype = {};
    Object.defineProperty(Foo.prototype, "constructor", {
      enumerable: false,
      writable: true,
      configurable: true,
      value: Foo
    });
    
    console.log(Foo.prototype.constructor === Foo); // true
    console.log(f.constructor === Foo); // true
    console.log(f.constructor === Foo.prototype.constructor); // true
  • 相关阅读:
    JavaScript 多个空格替换成1个空格
    「DIARY」NOI2021 小结
    kubernetes常用命令总结
    Qt绘图(使用QPainter)翻转图像的两种方法
    android 11 R framework 新特证 开发备忘
    浏览器的缓存机制
    记el-tree 懒加载复选框回显的坑
    VUE根据文件流下载EXC
    西瓜视频播放器VUE
    推荐系统打散算法--权重
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9816917.html
Copyright © 2011-2022 走看看