zoukankan      html  css  js  c++  java
  • 原型,原型对象,原型链,构造函数,继承(二)

    1.prototype(原型对象)有一个属性叫做constructor,constructor默认指向prototype(原型对象)所在的构造函数

    2.constructor属性是定义在prototype上的,那就意味着可以被实例对象所继承

    3.可以使用hasOwnProperty 方法来验证一个属性是自己的还是继承过来的

    4.constructor的作用:
      作用一:分辨实例对象到底属于哪个构造函数 instanceof()
      作用二:可以从一个实例对象创建另一个实例对象

         var Fun = function(){
                console.log('hello');
                console.log('world!');
            }
            var fun = new Fun();
            console.log(Fun.prototype.constructor === Fun); //true
            console.log(fun.constructor === Fun); //true
            console.log(Fun.prototype.hasOwnProperty("constructor")); // true
            console.log(fun.hasOwnProperty("constructor"));    //false
    
            console.log(fun instanceof Fun);//true
    
            var fun1 = new fun.constructor();
            console.log(fun1 instanceof Fun); //true
         Fun.prototype.createCopy = function(){
                console.log(this);
                console.log(this.constructor);
                return new this.constructor();
            }
            // this.constructor指向Fun , this指向调用者本身
            var fun2 = new Fun();
            console.log(fun2.constructor === Fun.prototype.constructor);//true
            console.log(fun2.constructor === Fun);//true
            console.log(fun2.createCopy().__proto__ === Fun.prototype);//true

    继承:

         function Father(){
                this.sex = '男';
            }
            function Son(){
                this.age = 24;
                Son.superclass.constructor.call(this);
            }
            Son.superclass = new Father();
            var son = new Son();
            console.log(son.age);
            console.log(son.sex);
            console.log(Son.superclass); //Father

    注意: 由于constructor属性是一种原型对象与构造函数的关联关系,所以我们修改原型对象的时候务必要小心

         function A(){
    
            }
            function B(){
    
            }
            var a = new A();
            A.prototype = B.prototype;
            console.log(a.constructor);
            console.log(a.constructor === A);//true
            console.log(a.constructor === B);//false
    
            console.log(a instanceof A);//false
            console.log(a instanceof B);//false
  • 相关阅读:
    快速实现一个带后端服务的 Vue 项目,用云开发Vue插件!
    做好内容安全检测,和风险说「再见」(下)!
    新能力|云调用支持微信支付啦!
    获奖结果公布|2020腾讯犀牛鸟云开发校园技术布道师养成计划
    SpringMVC原理及流程解析
    Mysql梳理-关于索引/引擎与锁
    写在庚子年之前
    Spring的BeanPostProcessor后置处理器与bean的生命周期
    AQS系列(六)- Semaphore的使用及原理
    AQS系列(五)- CountDownLatch的使用及原理
  • 原文地址:https://www.cnblogs.com/nlj-blog/p/7544626.html
Copyright © 2011-2022 走看看