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
  • 相关阅读:
    多线程(三)
    多线程(二)
    多线程(一)
    网络编程socket套接字及其使用(六)
    网络编程socket套接字及其使用(五)
    网络编程socket套接字及其使用(四)
    网络编程socket套接字及其使用(三)
    网络编程socket套接字及其使用(二)
    网络编程socket套接字及其使用(一)
    html快速入门
  • 原文地址:https://www.cnblogs.com/nlj-blog/p/7544626.html
Copyright © 2011-2022 走看看