zoukankan      html  css  js  c++  java
  • js原型链理解

    var friend = new Person(); 
    Person.prototype.sayHi = function(){ 
     alert("hi"); 
    }; 
    friend.sayHi(); //"hi"(没有问题!)

    重写整个原型链的prototype时,已经实例话的对象只能取之前的prototype对象。

    function Person(){ 
    } 
    var friend = new Person(); 
     
    Person.prototype = { 
     constructor: Person, 
     name : "Nicholas", 
     age : 29, 
     job : "Software Engineer", 
     sayName : function () { 
     alert(this.name); 
     } 
    }; 
    friend.sayName(); //error

     Object.create()是创建一个空对象,而空对象的原型(__proto__)指向传进来的参数

    总结:使用Object.create()是将对象继承到__proto__属性上

    复制代码
    var test = Object.create({x:123,y:345});
    console.log(test);//{}
    console.log(test.x);//123
    console.log(test.__proto__.x);//3
    console.log(test.__proto__.x === test.x);//true

    var test1 = new Object({x:123,y:345});
    console.log(test1);//{x:123,y:345}
    console.log(test1.x);//123
    console.log(test1.__proto__.x);//undefined
    console.log(test1.__proto__.x === test1.x);//false

    var test2 = {x:123,y:345};
    console.log(test2);//{x:123,y:345};
    console.log(test2.x);//123
    console.log(test2.__proto__.x);//undefined
    console.log(test2.__proto__.x === test2.x);//false

    new Object() 也就是具有构造函数的内置Object的实例,新创建的对象的__proto__属性会指向Object的prototype

     疑问

    function SuperType(){ 
     this.colors = ["red", "blue", "green"]; 
    } 
    SuperType.prototype.x=1;
    function SubType(){ 
     //继承了 SuperType 
     SuperType.call(this); 
    } 
    var instance1 = new SubType();
    
    

    得到的instance1为

    为什么SubType.prototype.__proto__是Object.prototype 而不是SuperType.prototype 且instance1.x为undefined

    要想实现继承需改成如下

    function SuperType(){ 
     this.colors = ["red", "blue", "green"]; 
    } 
    SuperType.prototype.x=1;
    function SubType(){ 
     //继承了 SuperType 
     SuperType.call(this); 
    } 
    SubType.prototype=new SuperType();
    SubType.constructor=SubType;
    或者
    SubType.prototype=Object.create(SuperType.prototype);
    SubType.constructor=SubType;
    var instance1 = new SubType();
  • 相关阅读:
    android判断服务是否是运行状态
    Android调用OCR识别图像中的文字
    Java生成各种条形码
    android 实现摇一摇功能
    【读书笔记】Html5游戏开发
    SpeechLib 语音播报
    罗盘
    注释文档在线编辑及生成
    系统空闲时间判断&命名验证
    Asp.Net MVC中使用ACE模板之Jqgrid
  • 原文地址:https://www.cnblogs.com/nanacln/p/11424830.html
Copyright © 2011-2022 走看看