原型链

    在讲原型链之前,我们首先要先来明确几个概念:类、对象、构造函数、原型

    类:具有相同特征(属性)和行为(方法)的事物的集合;js中对象的目的实际上就是将具有相同属性和行为的代码整合到一起,方便我们的管理。而构造函数实际上就是创建了一个类。那么如何创建一个构造函数呢,下面我举个例子给大家说明一下。

function Person(_name,_age,_height){
	this.name = _name;
	this.age = _age;
	this.height = _height;
	this.walk = function(){
		console.log("I can walk");
	}
}
var student = new Person("洋洋",18,160);
console.log(student.height);

  注意:构造函数的首字母一定要大写。构造函数的机制是会自动创建一个空对象,与this相关联,并将这个对象作为默认返回值返回。在上面的代码中Person就是一个构造函数,而student就是一个对象。

var student = new Person("洋洋",18,160);

student.walk();
var student1 = new Person("欢欢",19,168);
student.walk();

    现在我们来看一下student和student1表面上好像没什么问题,先创建对象再调用方法。但是实际上这样做,有一个很大的弊端。那就是对于每一个实例对象,walk()方法都是一模一样的内容,每一次生成一个实例,都必须为重复的内容,多占用一些内存。这样既不环保,也缺乏效率。这时候就该我们的原型出场啦,

Person.prototype = {	
	walk:function(){
		console.log("I can work");
	}
}

  如果将walk方法写到prototype中就解决了之前的问题,不会每次声明对象,调用walk 方法的时候都会占用内存。

     想必大家对原型这个概念已经有了了解,那么接下来就要引出我们今天讲的重点原型链。什么是原型链呢?所谓原型链指的是当对象尝试获取某个属性或者某个方法时,若该对象的构造函数没有,会到该构造函数的原型中去找,如果原型也没有,会去原型对象的原型去找最终到达Object.prototype。可能现在这句话大家还不能理解,那就举个例子来说明一下,一言不合就举例。

function Student(_name,_age,_height){
    this.name = _name;
    this.age = _age;
    this.height = _height;
    this.dance = function(){
        console.log("I can dance");
    }
}
Student.prototype = {
       dance:function(){
        console.log("I can dance,too");
    }
}
var student = new Student("洋洋",18,160);
student.dance();    

  因为构造函数中有dance()方法,所以打印的结果是:I can dance;

function Student(_name,_age,_height){
    this.name = _name;
    this.age = _age;
    this.height = _height;
  
}
Student.prototype = {
       dance:function(){
        console.log("I can dance,too");
    }
}
var student = new Student("洋洋",18,160);
student.dance();   

  因为构造函数中没有dance()方法,而Student的原型中有 walk()方法,所以打印结果是I can dance,too 

function Person(_name1,_age1,_height1){
this.name1 = _name1; this.age1 = _age1; this.height1 = _height1; } Person.prototype.dance = function(){ console.log("I can dance") } function Student(_name,_age,_height){ this.name = _name; this.age = _age; this.height = _height; } Student.prototype = new Person("123",12,135) ; var student = new Student("洋洋",18,160); student.dance();

   Student中没有dance()方法,Student中的原型中也没有dance()方法,所以只能去找Person的原型,打印结果为I can dance。

  通过这次的讲解你懂原型链了吗?

  

 

  

  

posted @ 2017-03-11 18:05  杨冬梅  阅读(132)  评论(0编辑  收藏  举报