首页 > 代码库 > javascript之原型

javascript之原型

 JavaScript 中,万物皆对象!但对象也是有区别的。分为普通对象和函数对象,Object ,Function 是JS自带的函数对象

  function Person(name){

    this.name = name;

  }

  Person.prototype.sayName = function(){

    console.log(this.name);

   };

  Person.prototype.changeName = function(name){

    this.name = name;

    console.log(this.name);

   };

  var person1 = new Person(‘demo‘);

    person1.sayName();

    person1.changeName (‘test‘);

    console.log(person1.name);

这里我们定义了一个构造函数Person,它的每个对象都有changeName和sayName两个方法。下面我们看原型继承:

  function Student(name){

    var learns = [];

    this.name = name;

    this.learn = function(learn){

      learns.push(learn );

    }  

  }

  Student.prototype = new Person();

  var student1 = new Student(‘student-001‘);

  student1.sayName();

  

  Student继承了Person,所以他拥有Person的所有特性。

 

javascript之原型