• JavaScript探究之原型对象


    JavaScript常被描述为一种基于原型的语言(prototype-based language),每个对象拥有一个原型对象,对象以其原型为模板、从原型继承属性和方法。

    原型对象也可以拥有原型,一层一层、以此类推。这种关系常被称为原型链(prototype chain)

    准确地说,这些属性和方法定义在Object的构造器函数(constructor functions)之上的prototype属性上,而非对象实例本身。


    一、寄生组合式继承

    借用构造函数继承属性借用原型链继承方法

    是实际开发中最常用的继承方法,也是ES5的最常用的继承方法。

     1 function Person(name){
     2   this.name=name;
     3 }
     4 Person.prototype.sayName=function(){
     5   console.log(this.name+' '+this.gender+' '+this.age);
     6 }
     7 function Female(name,gender,age){
     8   Person.call(this,name);//第一次调用父类构造函数             
     9   this.age=age;
    10   this.gender=gender;
    11 }
    12 Female.prototype.constrcutor=Female;//因重写原型而失去constructor属性,所以要对constrcutor重新赋值
    13 Female.prototype=new Person();//第一次调用父类构造函数 

    基本步骤可以总结为:

      1. 通过this构造对象属性,原型对象上构造对象方法
      2. 通过构造函数继承属性,通过原型链继承方法
      3. 对construcor重新赋值

      进一步可以封装为,

    function inheritPrototype(Female,Person){ 
          var protoType=Object.create(Person.prototype);
          protoType.constructor=Female;
          Female.prototype=protoType;
    }
    
    inheritPrototype(Female,Person);
    Female.prototype.sayAge=function(){
          console.log(this.name+' '+this.age);
    }
    var fm=new Female('skila','female',19);

    二、this关键字

    具体的使用情形如下:

    1. 全局环境: 指向全局对象(说明:浏览器中,全局对象为window;node中,全局对象为global)
    2. 函数(运行内环境):严格模式下为undefined,非严格模式下为全局对象
    3. call方法和apply方法:apply接受对象call接受多个参数,用于将this值绑定到特定对象中(即第一个参数中)
    4. bind方法:创建一个和目标函数具有相同函数体和作用域的函数,需要调用才能使用
    5. 箭头函数:箭头函数没有原型对象,与封闭词法环境中的this保持一致,全局代码中,被设置为全局对象
    6. 对象的方法:函数作为对象里的方法被调用,this指向调用该函数的对象
    7. 原型链中的this:原型链某处定义的方法,this指向调用改方法的对象
    8. getter和setter中的this:用getter和setter的函数都会把this绑定到设置或获取属性的对象
    9. 构造函数中:当一个函数用作构造函数时(使用new关键字),this被绑定到正在构造的新对象
    10. DOM事件处理函数:函数用作事件处理函数,this指向触发事件的元素(e.currentTarget)
    11. 内联事件处理函数:被内联on-event处理函数调用时,它的this指向监听器所在的DOM元素

     

    三、一些方法的实现流程

       new方法

       call方法

       bind方法

  • 相关阅读:
    [Linked List]Convert Sorted List to Binary Search Tree
    [Linked List]Reorder List
    [Linked List]Insertion Sort List
    解剖Nginx·模块开发篇(4)模块开发中的命名规则和模块加载与运行流程
    解剖Nginx·模块开发篇(3)ngx_http_hello_world_module 模块的基本函数实现
    解剖Nginx·模块开发篇(2)ngx_http_hello_world_module 模块基本结构定义
    解剖Nginx·模块开发篇(1)跑起你的 Hello World 模块!
    Nginx 源码完全注释(11)ngx_spinlock
    Nginx 源码完全注释(10)ngx_radix_tree
    Nginx源码完全注释(9)nginx.c: ngx_get_options
  • 原文地址:https://www.cnblogs.com/bearRunning/p/12220761.html
Copyright © 2020-2023  润新知