functionPerson(){ this.name = 'attr jack'; this.eat = function(){ console.log('method eat'); }; } var person = new Person(); console.log(person.name); console.log(person.eat());
原型方式
把属性和方法的定义放到prototype上
1 2 3 4 5 6 7 8
functionPerson(){} Person.prototype.name = 'attr name'; Person.prototype.eat = function(){ console.log('method eat') } var person = new Person(); console.log(person.name); console.log(person.eat());
构造函数+原型混合方式
1 2 3 4 5 6 7 8 9
functionPerson(){ this.name = 'attr name'; } Person.prototype.eat = function(){ console.log('method eat') } var person = new Person(); console.log(person.name); console.log(person.eat());
Object.create()法
Es6的一个新的方法Object.create(),直接返回一个对象。
1 2 3 4 5 6 7 8 9
var Person = { name: 'attr name', eat: function(){ console.log('method eat') } } var person = Object.create(Person); console.log(person.name); console.log(person.eat());