Javascript 原型和原型链

先来了解一下Javascript中的原型:”原型也是一个对象,原型能够用来实现继承。。。“javascript

对于 原型,构造函数,以及实例之间的关系:“每一个(构造)函数都有一个原型属性,原型对象都包含一个指向构造函数的指针,每一个实例都包含一个指向原型对象的指针。”java

 举个例子:函数

1       function Student(name) {
2           this.name = name;
3       }
4       var stu = new Student("xiao ming");

Student 函数有个prototype的属性,它指向Student的原型对象。Student的原型对象 包含一个constructor的属性 和 一个 __proto__ 的属性. constructor属性指向Student 函数, __proto__指向Object的原型(在javascript中全部对象都是继承Object)。Student 函数如图所示:this

 在代码中咱们还建立了一个Student函数的实例 stu, 它会有一个指针__proto__指向Student 原型对象.spa

注意:stu 中会多一个name 属性,属性是存在于实例中,而不是函数,或者函数的原型中,这点很是容易出错。stu 实例 以下图:prototype

因此,前面例子整个的对象示意图 就是:指针

原型链:若是把构造函数(A)的实例赋给另外一个构造函数(B)的原型,那么函数B, 函数A的实例, 以及函数A之间就会造成一个原型链。B的实例就会继承A的全部属性和方法。code

若是此时咱们把stu 再赋给其它对象的原型,从图中能够看出,红色线条部分就会造成一个原型链。对象

用原型链实现继承的例子:blog

      function Person() {
          this.hasFriends = true;
          this.friends = ["David"];
      }
      Person.prototype.getHasFriend = function () {
          alert(this.hasFriends);
      }
      function Student() {
          this.hasGF = false;
      }
      Student.prototype = new Person();
      Student.prototype.getScore = function () {
          alert(this.hasGF);
      }
      var stu = new Student();
      stu.getFriends();
      stu.friends.push("Lily");
      var newStu = new Student();
      alert(newStu.friends);
相关文章
相关标签/搜索