实例对象中有个属性,proto,也是对象,叫原型,不是标准属性,浏览器使用的
构造函数中有一个属性,prototype,也是对象,叫原型,是标准属性,程序员使用
实例对象的原型__proto__和构造函数的原型prototype指向是相同的
实例对象中的__proto__原型指向的是构造函数中的原型prototype
console.log(per.__proto__==Person.prototype);
原型的作用:共享数据,节省内存空间。
<script>
function Person(name,age){
this.name=name;
this.age=age;
}
//通过原型来添加方法,解决数据共享
Person.prototype.band=function(){
console.log("看脚下一片灰暗,望头顶星光璀璨");
};
var p1=new Person("子健",2019);
var p2=new Person("石璐",2019);
console.log(p1.band==p2.band);
</script>
<script>
//构造函数
function Person(sex,age){
this.sex=sex;
this.age=age;
}
//通过原型添加方法
Person.prototype.sayHi=function(){
console.log("Hello, World");
};
var per=new Person("男",20);
console.dir(per.__proto__.constructor==Person.prototype.constructor);//实例对象
console.dir(Person);//构造函数的名字
var per2=new Person("女",30);
console.log(per.sayHi);
</script>
面向对象思想是抽象的过程,实例化的过程:按钮是一个对象,div是一个对象,颜色是一个属性
<script>
function Changestyle(btnId,dvId,color){
this.btnObj=document.getElementById(btnId);//按钮对象
this.dvObj=document.getElementById(dvId);//div对象
this.color=color;//颜色
}
//数据共享来改变背景颜色
Changestyle.prototype.init=function(){
console.log(this);
};
//实例化对象
var cs=new ChangeStyle("btn","dv","yellow");
cs.init();
function Person(){
this.sayHi=function(){
console.log(this);
};
}
var p=new Person();
p.sayHi();
</script>
面向过程和面向对象
<script>
function ChangeStyle(btnObj, dvObj, json){
this.btnObj=btnObj;
this.dvObj=dvObj;
this.json=json;
}
ChangeStyle.prototype.init=function(){
//点击按钮,改变div多个样式属性值
var that=this;
this.btnObj.onclick=function(){//按钮
for(var key in that.json){
that.dvObj.style[key]=that.json[key];
}
};
};
//实例化对象
var json={"width":"500px","height":"800px","backgroundColor":"blue","opacity":"0.2"};
var cs=new ChangeStyle(my$("btn"),my$("dv"),json);
cs.init();//调用方法
</script>
实例对象和构造函数之间的关系:
1.实例对象是通过构造函数来创建的——创建过程叫实例化
2.判断对象是不是这个数据类型:
(1)通过构造器的方式:实例对象.构造器==构造函数名字
(2)对象instanceof构造函数名字
尽可能使用第二种方式来辨别。
通过构造函数实例对象,并初始化
<script>
var arr=new Array(10,20,30,40);
//join是方法,实例对象调用的方法
arr.join("");
console.dir(arr);
//join方法在实例对象__proto__原型
console.log(arr.__proto__==Array.prototype);
</script>