1、prototype原型对象
js规定,每个构造函数都有一个prototype,其实prototype就是一个对象,这个对象的属性和方法都会被构造函数所拥有。
我们可以把那些不变的方法定义在prototype对象上,其实所有对象的实例就可以共享这些方法。
话不多说,上代码。
<script>
function Person(name,age){
this.name=name
this.age=age
this.hobby=function(){
console.log("唱歌")
}
}
var xm=new Person('小明','10')
var xh=new Person('小红','12')
console.log(xm.hobby===xh.hobby) //输出false
xm.hobby()//唱歌
xh.hobby()//唱歌
</script>
es6之前是把方法写在构造函数里面,每个对象都会去开辟一个函数的内存空间,所以xm.hobby===xh.hobby比较会返回false,如果有多个对象,这样做会存在浪费内存空间,下面建议用prototype对象
<script>
function Person(name,age){
this.name=name
this.age=age
}
Person.prototype.hobby=function(){
console.log("唱歌")
}
var xm=new Person('小明','10')
var xh=new Person('小红','12')
console.log(xm.hobby===xh.hobby) //输出true
xm.hobby()//唱歌
xh.hobby()//唱歌
</script>
此时hobby为同一个方法,所以xm.hobby===xh.hobby返回true
一般来说,公共属性定义在构造函数里面,公共方法定义在原型对象身上
2、_proto_对象原型
其实在每个对象中会有一个_proto_属性指向我们的构造函数的原型对象prototype
<script>
function Person(name,age){
this.name=name
this.age=age
}
Person.prototype.hobby=function(){
console.log("唱歌")
}
var xm=new Person('小明','10')
var xh=new Person('小红','12')
console.log(xm._proto_===Person.prototype) //输出true
</script>
hobby()方法的查找规则:首先看看xm对象身上是否有hobby方法,如果有就执行它,如果没有,因为有_proto_的存在,就会去构造函数原型对象prototype身上去查找。
3、原型constructor构造函数
<script>
function Person(name,age){
this.name=name
this.age=age
}
Person.prototype={//如果我们修改了原来的原型对象,给原型对象赋值的是一个对象,则必须手动的利用constructor指回原来的构造函数。
constructor:Star,
hobby1:function(){
console.log("唱歌")
}
hobby2:function(){
console.log("跳舞")
}
}
var xm=new Person('小明','10')
var xh=new Person('小红','12')
console.log(xm.prototype.constructor)
console.log(Star.prototype.constructor)
</script>