[js学习笔记] 原型链理解

js中只有对象,包括对象,函数,常量等。

prototype

  • 只有函数里有这个属性。
  • 对象里可以设置这个属性,但是没这个属性的意义
  • prototype指向一个对象,可以添加想要的方法。
  • 该对象里有一个constructor属性,默认指向了这个函数。

proto

  • 对象里有这个属性。
  • 功能: 如果要一个对象的属性,会先在这个对象里查找,如果这个对象里没有这个属性,则会在这个对象里__proto__的对象里查找这个属性
  • 如果这个对象本身还有一个 proto 属性,则会继续在__proto__.__proto__ 里找这个属性。
  • 该属性无法在ie11以下,无法直接访问

new 对象

  • new function 创建对象的时候,会首先创建一个空对象
  • 传入这个fuction赋值给this对象
  • 把该function里的prototype 赋值给这个对象的 __proto__属性。
  • 所创建出来的对象,这是为什么创建出来的对象可以访问之前function里prototype设置属性

一些实例

  • proto

    var a = {};
    a.__proto__ = {
    	"show":function(){
    		document.write("show");	
    	}	
    }
    a.show()//show
    
  • function 里

    function B(){
    	
    }
    B.prototype.show1 = function(){
    	document.write("B:show1");
    }
    B.show = function(){
    	document.write("B:show");	
    }
    new B().show1();// 对象只与方法里prototype 关联
    new B().show();//B对象里直接设置的方法不会关联到方法里。
    
  • 方法调用以及this理解

    • this 其实就是调用方法 . 之前的对象。
    • 如果使用call,apply方式调用,则this是用第一个参数赋的值。
    function B(){
    	
    }
    B.show = function(){
    	document.write(this);	
    }
    
    B.show();//打印结果为: function B
    

基础的东西都说完了,咱们来基于这些做一些拓展

继承封装

  • 方式1

    ext = function(child,parent)
    {
    	var _proto = function(){};
    	_proto.prototype = parent.prototype;
    	child.prototype = new _proto();
    	child.prototype.constuctor = child;
    	child.super=parent;
    }
    Object.prototype.super = function(){};
    
  • 方式2

    ext = function(child,parent)
    {
    	child.prototype.__proto__ = parent.prototype;//new _proto();
    	child.prototype.constuctor = child;
    	child.super=parent;
    }
    Object.prototype.super = function(){};
    
  • 使用

    //定义Person
    function Person(name, age)
    {
    	this.name = name;
    	this.age = age;
    }
    
    Person.prototype.speak = function()
    {
    	document.write("name = "+this.name + "<br/>");	
    }
    
    
    //定义学生,继承了Person
    function Student(name,age)
    {
    	Student.super.call(this,name,age);
    	this.score = 90;
    }
    ext(Student,Person)
    
    
    Student.prototype.show = function()
    {
    	document.write("show name=" + this.name + ",score = "+this.score +"<br/>");	
    }
    
    
    
    //定义Academician 继承Student
    function Academician(name, age){
    	Academician.super.call(this,name,age);
    }
    ext(Academician,Student);
    
    
    var academ = new Academician("狗蛋",20);
    
    academ.show();
    academ.speak();
    
  • 打印结果

    show name=狗蛋,score = 90
    name = 狗蛋
    
原文地址:https://www.cnblogs.com/boliu/p/5967716.html