function createPerson (name, age, job) { var o = new Object() o.name = name o.age = age o.job = job o.sayName = function () { console.log(this.name) } o._this = this return o }
var p = createPerson('chris', 18, 'softwate engineer') p.sayName() console.log(p._this === this) // 这里的Person 的 this 指向windows全局
function Person(){} Person.prototype.name = 'chris' Person.prototype.age = 18 Person.prototype.sayName = function () { console.log(this.name) } var p1 = new Person() p1.sayName() var p2 = new Person() p2.sayName() console.log(p1.sayName() === p2.sayName())
使用字面量 构建原型
1 2 3 4 5 6 7 8 9 10 11 12 13 14
function Person(){} Person.prototype = { constructor: Person, // 使用过prototype等于重写了整个原型对象,所以需要在构造方法中重新指向Person() name: 'chris', age: 18, sayName: function () { console.log(this.name) } } var p1 = new Person() p1.sayName() var p2 = new Person() p2.sayName() console.log(p1.sayName() === p2.sayName())