目录
一、原型:
1、原型对象:每个构造函数(类 )都有一个原型对象(默认存在),公司原型对象可以通过prototype属性进行访问。
(1)构造方法的原型对象是object类型:
(2)prototype的属性是默认存在的
(3)原型对象的作用:
A.共享方法
function Person(name){ //ES5(ECMAScript5)语法:Person是类的名字(构造方法名)
this.name = name;
function sayHello(){
console.log("西安邮电大学")
}
}
//输出Person的原型对象
console.log("Person的原型对象:",Person.prototype);
//构造方法的原型对象是什么类型的
console.log("原型对象的类型:",typeof Person.prototype);
var p1 = new Person("张三");
var p2 = new Person("李四");
console.log(p1.sayHello === p2.sayHello)
//通过原型对象给Person增加方法
Person.prototype.showAddress = function(address){
console.log("地址:",address);
}
p1.showAddress("长安区")
p2.showAddress("雁塔区")
console.log(p1.showAddress === p2.showAddress)
Person.prototype.showName = function(){
console.log("姓名:",this.name)
}
p1.showName();
p2.showName();
2、对象的原型对象:每个对象都有一个默认的属性__proto__属性,该属性指向对象的原型对象
class Person{
constructor(name,address){
this.name = name;
this.address = address;
}
sayHello(){
console.log("你好!")
}
}
console.log(Person.prototype);//输出Person类的原型
Person.prototype.showName = function(){
console.log("姓名:",this.name)
}
Person.prototype.showAddress = function(){
c