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的原型中,故引用地址是一樣的。
}
網(wǎng)站標(biāo)題:JS面向?qū)ο?/a>
當(dāng)前路徑:http://m.rwnh.cn/article24/pdidje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、品牌網(wǎng)站設(shè)計(jì)、靜態(tài)網(wǎng)站、微信小程序、服務(wù)器托管、網(wǎng)頁(yè)設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)