什麼是“構造函數”?
構造函數其實就是一個普通的函數,但是在這個函數體中使用了 "this" 這個變量。我們向構造函數使用
new 運算符,就能生成實例化對象,並且這個
this 變量會綁定在這個new出來的實例化對象上。
關鍵:
1、函數中的 "this" 指向的是實力化的對象。
2、實例化的對象是我們在構造函數的基礎上使用 new 運算符生成的。
例如:
//定義一個構造函數
function myfile(name,work){
this.name = name;
this.work = work;
this.type = "person";
this.sex = function(){alert("nan")};
}
var myfile1 = new myfile("zhang","IT");
//new 一個實例化對像。
alert(myfile1.name); //zhang
alert(myfile1.type); //person
myfile1.sex(); //nan
總結:this指向的new出來的實例化對象。
上面的實例中有一個問題,就是 this.type = "person" this.sex = function(){alert("nan")};這兩個的值是寫死在構造函數中的,不夠靈活,如果我們想要重複調用,這時this.type與this.sex的侷限性就會很大。
解決方法:
我們可以使用:prototype 原型模式
Prototype 模式
在javascript中,每一個構造函數都有一個 prototype屬性,指向另一個對象。被指向的這個對象的所有屬性和方法,都會被構造函數的實例化對象所繼承。
所以我們可以用 Prototype 模式來解決上面的不靈活問題,即部分不變的屬性和方法我們可以定義在prototype對象上。
例如:
//創建構造函數
function myfile(name,work){
this.name = name;
this.work = work;
}
myfile.prototype.type = "person"; //在prototype對象上來定義不變屬性 type
myfile.prototype.sex = function(){alert("nan")};
//在prototype對象上來定義不變屬性 sex
var myfile1 = new myfile("zhang","IT");
//new 一個實例化的對象
alert(myfile1.type); //person
myfile1.sex(); //nan
<!--簡單的封裝實例-->
<button
class="btn">按鈕1</button>
<button
class="btn">按鈕2</button>
<button
class="btn">按鈕3</button>
<button
class="btn">按鈕4</button>
<button
class="btn">按鈕5</button>
<script>
var
aBtn
= document.getElementsByTagName("button");
function
myBtn(type){
this.type
=
function(){
for
(var
i=0;i<type.length;i++){
type[i].onclick
=
function(){
alert(this.innerHTML);
}
}
};
}
var
myfile1
= new
myBtn(aBtn);
myfile1.type();
</script>
Prototype模式的驗證方法
1、isPrototypeOf()用於判斷某個原型對象 即 proptotype 對象和某個實例之間的關係。
例如:
function myfile(name,work){
this.name = name;
this.work = work;
}
myfile.prototype.type = "person";
myfile.prototype.work = function(){alert("IT");}
var myfile1 = new myfile("zhang","IT");
alert(myfile.prototype.isPrototypeOf(myfile1));
//true
2、每一個實例化對象都有一個hasOwnProperty()方法。
返回一個布爾值,指出一個對象是否具有指定名稱的屬性。
object.hasOwnProperty(proName)
參數
object
必選項。一個對象的實例。
proName
必選項。一個屬性名稱的字符串值。
說明
如果
object 具有指定名稱的屬性,那麼 hasOwnProperty 方法返回
true;反之則返回 false。此方法無法檢查該對象的原型鏈中是否具有該屬性;該屬性必須是對象本身的一個成員。
例如:
function myfile(name,work){
this.name = name;
this.work = work;
}
myfile.prototype.type = "person";
myfile.prototype.work = function(){alert("IT");}
var myfile1 = new myfile("zhang","IT");
alert(myfile1.hasOwnProperty("type"));
//false
alert(myfile1.hasOwnProperty("name"));
//true
注意:hasOwnProperty()方法必須是對象本身的一個成員,無法檢查出該對象原型鏈中的屬性,如上例所示,alert(myfile1.hasOwnProperty("type"));
返回的是false因爲type是使用原型鏈prototype添加的屬性,而alert(myfile1.hasOwnProperty("name"));返回的是true,因爲name是對象本身的屬性。
3、in運算符
1、可以用來判斷一個實例化對象中是否含有某個屬性,無論是不是本地的。
2、用for.....in來遍歷某個實例化對象的所有屬性。
function myfile(name,work){
this.name = name;
this.work = work;
}
myfile.prototype.type = function(){alert("person");}
var myfile1 = new myfile("zhang","IT");
alert("work" in myfile1);
//使用in來判斷work裏是不是有name這個屬性:
for (var a in myfile1){
//使用in來循環myfile1裏的所有屬性:
alert(a);
alert("myfile1["+a+"]="+myfile1[a]);
}