1、
function A(){}
A.prototype={
aa:"aa",
method:function(){}
}
var a = new A();
var b = new A();
console.log(a.aa==b.aa); //true
console.log(a.method==b.method); //true
console.log("a.aa="+a.aa+" b.aa="+b.aa) //a.aa=aa b.aa=aa
分析:prototype原型的意思,这是JS创建对象方法之一的原型法。如果使用原型法定义对象,那么生成的所有对象都会共享原型中的属性。
因为使用原型方式,a和b指向同一个原型,即对应了同一个对象属性。
2、
function A(){}
A.prototype={
aa:"aa",
method:function(){}
}
var a = new A();
var b = new A();
b.aa = "bb";
b.method=function(){console.log("b method change")}
console.log(a.aa==b.aa); //false
console.log(a.method==b.method); //false
console.log("a.aa="+a.aa+" b.aa="+b.aa) //a.aa=aa b.aa=bb
console.log("a.method="+a.method+" b.method="+b.method) //a.method=function (){} b.method=function (){console.log("b method change")}
分析:a 和 b指向同一个原型,我的理解是,如果实例对象修改了原型的内容,则依实例对象为准。
3、
function A(){
var count = 0;
this.aa = "aa";
this.method = function(){
return count;
}
this.obj={}
}
A.prototype={
aa:"cc",
method:function(){}
}
var a = new A;
var b = new A;
console.log(a.aa==b.aa); //true
console.log(a.obj==b.obj); //false
console.log(a.method==b.method); //false
console.log("a.aa="+a.aa+" b.aa="+b.aa); //a.aa=aa b.aa=aa
console.log("a.method="+a.method+" b.method="+b.method) //a.method=function (){return count;} b.method=function (){return count;}
分析:这是一个优先级的问题,JS用prototype创建对象,是有优先级的,如果存在构造方法就先使用构造方法,没有构造方法则使用prototype方法。