window.onload=function(){
//1.工厂模式:
function student1(name,qq){
var obj=new Object();
obj.name=name;
obj.qq=qq;
obj.show=function(){
alert(this.name+":"+this.qq);
}
return obj;
}
var s1=student1("HH","123");
console.log(s1);
//2.构造函数:
function Student2(name,qq){
this.name=name;
this.QQ=qq;
this.show=function(){
alert(this.name+":"+this.QQ);
}
}
var s2=new Student2("HH","1234");
console.log(s2);
//3.字面量方式:
var s3={
"name":"HH",
"QQ":"12345",
show:function(){
alert(this.name+":"+this.QQ);
//alert(name+":"+QQ);//错误!!!
}
}
//s3.show();
//console.log(s3.name+":"+s3.QQ);
console.log(s3);
//我们在定义函数的时候,函数本身就会默认有一个prototype的属性,而我们用new运算符来生成一个对象的时候就没有prototype属性。如:
console.log(s1.prototype);//undefined;
console.log(student1.prototype);//Object;
console.log(s2.prototype);//undefined;
console.log(Student2.prototype);//Object;
console.log(s3.prototype);//undefined;
function Student4(){ };
Student4.prototype = {
name:"fdf",
age:"fd",
//字面量创建的方式使用constructor属性不会指向实例 而是指向object
// 强制修改
constructor :Student
};
var s4 = new Student();
alert(s4.constructor);
}
window.onload=function(){
function Student(){};
Student.prototype.name="HH";
Student.prototype.show=function(){
alert("I am "+this.name);
}
var s=new Student();
//s.show();
//alert(s.name);
Student.prototype.name="FF";
//alert(s.name);
//原型方式创建对象的缺陷:1.不能传参; 2.一改全改
function Student1(){
this.name="FF";
};
Student1.prototype.name="HH";
Student1.prototype.show=function(){
alert("I am "+this.name);
}
var s1=new Student1();
console.log(s1.name);//FF
console.log(s1.__proto__.name);//HH
console.log(Student1.prototype.name);//HH
Student1.prototype.name="O_O";
console.log(s1.name);//FF
console.log(s1.__proto__.name);//O_O
console.log(Student1.prototype.name);//O_O
//通过原型改变的属性和方法不会改变对象原有的属性和方法
}
window.onload=function(){
//混合模式: 构造函数+原型
function Student(name,QQ){
this.name=name;
this.QQ=QQ;
if(typeof this.show != "function"){
Student.prototype.show=function(){
//alert(this.name+":"+this.QQ);
console.log(this); // this指s1
}
}
}
var s1=new Student("MM","1242");
s1.show();
var s2=new Student("QQ","w809r809ew");
console.log(s1.show==s2.show);//true;通过Student创建的对象共用函数show,其保存在Student的原型中,故引用地址是一样的。
}