【基础】JS查缺补漏1(原型)
先看示例:
const person = {
arms: 2,
legs: 2
}
// 通过 Object.create 将 person 设为 father 的原型
const father = Object.create(person)console.log(father) //{}
console.log(father.arms) //2
console.log(father. __proto__ === person) //true// Object.create 第二个参数可以设定属性
const son = Object.create(father, {
name: {
value: "xixi",
enumerable: true
}
})
console.log(son.__proto__ === father) //true
console.log(son.__proto__.__proto__ === person) //true这种基于原型创建对象的方法类似克隆羊,被克隆的对象就是原型对象。
优势是简单,劣势是不能像传统面向对象语言那样,通过类批量创造对象。所以后来有了通过构造函数创建对象:
function Computer (name, price){
this.name = name
this.price = price
}
// 将方法挂到原型对象上
// prototype 是实例对象的原型对象
Computer.prototype.showPrice = function(){
}
const apple = new Computer("苹果", 15000)每个对象都有一个原型对象,可以通过__proto__属性访问对象的原型对象。
构造函数的 prototype 指向一个对象,该对象是实例对象的原型对象。
原型对象的 constructor 属性指向其构造函数