zoukankan      html  css  js  c++  java
  • JavaScript prototype背后的工作原理

    首先从一个函数说起
    
    function fn1(name, age) {
    
      this.name = name;
      this.age = age;
    
      this.say = function() {
        alert('my name:' + this.name + 'and age:'+ this.age);
        
       }
    
    }
    
    fn1.prototype.test = function() {
        alert('test');
    }
    
    var f1 = new fn1('jm',20);
    
    f1.say(); //弹出 my name jm and age 20
    
    f1.test(); //弹出test
    这里发生什么事情?

    一些其本的东西 我们要知道 每个函数(function)都有一个保留属性 prototype 它返回的是一个对象

    这个对象可以写也可以读

    每个函数new 出来的对象有一个隐式属性 (__proto_ = fn1.prototype)指向构造函数的原型的!

    下面一个图说明prototype动行原理,(图中有参考网上一些资料):

  • 相关阅读:
    WinCE 与通讯模块
    6174问题
    阶乘因式分解(一)
    三个数从小到大排序
    公约数和公倍数
    水仙花数
    韩信点兵
    5个数求最值
    求转置矩阵问题
    孪生素数问题
  • 原文地址:https://www.cnblogs.com/yzenet/p/4431334.html
Copyright © 2011-2022 走看看