• 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();
  • 相关阅读:
    去哪网 2014.9.25 笔试题
    关于 Private strand flush not complete
    以太网数据帧相关
    Java根据年份算出所属的生肖。
    DWR常用<init-param>参数
    更新ORACLE数据时遇到锁死情况的处理
    Debug of bash , perl and python
    2013长沙网络赛H题Hypersphere (蛋疼的题目 神似邀请赛A题)
    I.MX6 wm8962 0-001a: DC servo timed out
    I.MX6 U-boot PWM hacking
  • 原文地址:https://www.cnblogs.com/nanacln/p/11424830.html
Copyright © 2020-2023  润新知