您好,登錄后才能下訂單哦!
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.構(gòu)造函數(shù):
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);//錯(cuò)誤?。。? }
}
//s3.show();
//console.log(s3.name+":"+s3.QQ);
console.log(s3);
//我們?cè)诙x函數(shù)的時(shí)候,函數(shù)本身就會(huì)默認(rèn)有一個(gè)prototype的屬性,而我們用new運(yùn)算符來生成一個(gè)對(duì)象的時(shí)候就沒有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",
//字面量創(chuàng)建的方式使用constructor屬性不會(huì)指向?qū)嵗? 而是指向object
// 強(qiáng)制修改
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);
//原型方式創(chuàng)建對(duì)象的缺陷: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
//通過原型改變的屬性和方法不會(huì)改變對(duì)象原有的屬性和方法
}
window.onload=function(){
//混合模式: 構(gòu)造函數(shù)+原型
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創(chuàng)建的對(duì)象共用函數(shù)show,其保存在Student的原型中,故引用地址是一樣的。
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。