共计 1616 个字符,预计需要花费 5 分钟才能阅读完成。
咱们在开发的过程中, 可能会应用到继承, 上面我来分享一下原型式继承, 心愿对你有所帮忙。原型式继承式一种不波及严格意义上构造函数的继承办法。即便不自定义类型血液能够通过原型实现对象之间的信息共享。
1. 给出一个函数:
function object(o){function F(){} | |
F.prototype=o; | |
return new F();} |
这个 object()函数会创立一个长期构造函数, 将传入的对象赋值给这个构造函数的原型, 而后返回这个长期类型的一个实例。实质上,object()式传入的对象执行了一次浅赋值。
2. 例子:
let person={ | |
name:"Nicholas", | |
friends:["Shelby","Court","Van"] | |
}; | |
let anotherPerson=object(person); | |
anotherPerson.name="Greg"; | |
anotherPerson.friends.push("Rob"); | |
let yetAnotherPerson=object(person); | |
yerAnotherPerson.name="Linda"; | |
yetAnotherPerson.friends.push("Barbie"); | |
console.log(person.friends); // "Shelby,Court,Van,Rob,Barbie" |
举荐的原型式继承实用于这种状况: 你有一个对象, 想在它的根底上再创立一个新对象。你须要把这个对象先传给 object(), 而后再对返回的对象进行适当批改。再这个例子中,person 对象定义了另外一个对象也应该共享的信息, 把它传给 object()之后会返回一个新对象。这个新对象的原型是 person 的属性, 也会跟 anotherPerson 和 yetAnotherPerson 共享。这里实际上克隆了两个 person。
3.ECMAScript5 通过减少 Object.create()办法将原型式继承的概念规范化了。这个办法承受两个参数: 作为新原型对象, 以及给新对象定义额定属性的对象 (第二个可选)。在只有一个参数时,Object.create() 与这里的 object()办法成果雷同:
let person={ | |
name:"Nicholas", | |
friends:["Shelby","Court","Van"] | |
}; | |
let anotherPerson=Object.create(person); | |
anotherPerson.name="Greg"; | |
anotherPerson.friends.push("Rob"); | |
let yetAnotherPerson=Object.create(person); | |
yetAnotherPerson.name="Linda"; | |
yetAnotherPerson.friends.push("Barbie"); | |
console.log(person.friends); // "Shelby,Court,Van,Rob,Barbie" |
4.Object.create()的第二个参数与 Object.defineProperties()的第二个参数一样: 每个新增属性都通过各自的形容来形容。以这种形式增加的属性会遮蔽原型对象上的同名属性。比方:
let person={ | |
name:"Nicholas", | |
friends:["Shelby","Court","Van"] | |
}; | |
let anotherPeron=Object.create(person,{ | |
name:{value:"Greg"} | |
}); | |
console.log(anotherPerson.name); // "Greg" |
原型式继承非常适合不须要独自创立构造函数, 但依然须要在对象间共享信息的场合。但要记住, 属性中蕴含的援用值始终会在相干对象间共享, 跟应用原型模式是一样的。
5. 本期的分享到了这里就完结啦, 心愿对你有所帮忙, 让咱们一起致力走向巅峰!
正文完
发表至: javascript
2020-12-30