functionPerson () { } Person.prototype = { age: 11, name: 'David', sayHi () { console.log('Hi') }, constructor: Person } let p1 = newPerson()//全都使用默认值 let p2 = newPerson() p2.age = 12//直接设定对象上的属性屏蔽原型上的值
缺点:全都是共享变量,如果对于类成员是复杂变量的,要进行覆盖不符合一般逻辑
3.原型和构造两个模式组合使用
上面两种组合使用,对于一般而言需要共享的,就放在原型链上;对于不需要共享的,就放在方法中
1 2 3 4 5 6 7 8 9 10 11
functionPerson (age,name) { this.age = age this.name = name } Person.prototype = { sayHi () { console.log('Hi,My name is',this.name) }, constructor: Person } let p = newPerson(11,'David')
functionPerson (age, name) { this.age = age this.name = name if (typeofthis.sayHi != 'function') {//仅在第一次调用构造函数时运行一次此代码 Person.prototype.sayHi = function () { console.log('Hi,My name is', this.name) } } } let p = newPerson(11, 'David')
functionPerson (age, name) { const o = newObject() o.age = age o.name = name o.sayHi = function () { console.log('Hi,My name is', this.name) } return o } let p = newPerson(11, 'David') p.sayHi()
functionPerson (age, name) { const o = newObject() let _age = age//不使用this,仅仅利用闭包保存这个变量 let _name = name o.sayHi = function () { console.log('Hi,My name is', _name) } o.setName = function (name) { _name = name } return o } let p = Person(11, 'David') p.setName('Davd') p.sayHi()
缺点:和5一样同样无法使用instaceof,是一种比较特殊的构造对象的方式
继承对象方法
1.原型链
复杂的原型链模式,其精华在于Son.prototype = new Father(),将Son的原型替换为了一个father的实例。根据instanceof的运算规则,可以判定Son的实例为Son/Father/Object
functionF(name,age){ this.name = name this.age = age this.sayHi = function(){ console.log('Hi,my name is', name) } } let father = newF('David',11) functionSon(father){ let clone = Object.create(father) clone.sayHi = function(){ console.log('Hi,i\'m a student,my name is', this.name) } return clone } let son = newSon(father) son.sayHi() console.log(son instanceof F)