js高级_98、函数的prototype
函数的prototype属性
*①
每个函数都有一个prototype属性,它默认指向一个Object空对象(即称为:原型对象),比如我们新建了一个函数,没有向函数的原型对象中添加属性和方法时,这个prototype指向的Object空对象里就没有我们的属性。
console.log(Date.prototype,typeof Date.prototype);
function Fun(){
}
console.log(Fun.prototype);
这是Date对象的原型
这是自定义fun函数的原型(没有属性,因为我们并没有给该函数原型对象里添加属性和方法)
*②
原型对象中有一个属性constructor,它指向函数对象,如图:
function Fun(){
}
console.log(Fun.prototype.constructor===Fun);//true
console.log(Date.prototype.constructor===Date);//true
2 给原型对象添加属性(一般都是方法)
*作用:函数(构造函数)的所有实例对象自动拥有原型对象中的属性(或方法)
function Fun(){
this.asb=function(){
console.log('word');
}
}
//给原型对象添加属性(一般是方法) ===>实例对象可以访问
Fun.prototype.sayhello=function(){
console.log('hello');
}
//实例
var fun=new Fun();
//调用原型中的方法
fun.sayhello();
最后输出结果为hello
这时候输出构造函数的原型对象可以看到我们刚刚添加的那个方法
console.log(Fun.prototype);