更新時間:2021-05-21 來源:黑馬程序員 瀏覽量:
Javascript創(chuàng)建對象的方式有哪些?下面介紹javascript中最常用的創(chuàng)建對象的六種方式。
代碼如下
var Cat = {}; //JSON
Cat.name="kity"; //添加屬性并賦值
Cat.age=2;
Cat.sayHello=function(){
alert("hello "+Cat.name+",今年"+Cat["age"]+"歲了"); //可以使用“.”的方式訪問屬性,也可以使用 HashMap 的方式訪問
}
Cat.sayHello(); //調用對象的(方法)函數(shù)2.1)創(chuàng)建一個對象,相當于 new 一個類的實例(無參構造函數(shù))
代碼如下
function Person(){
}
var personOne=new Person(); //定義一個 function,如果有 new 關鍵字去"實例化",那么該 function 可以看作是一個類
personOne.name="dylan";
personOne.hobby="coding";
personOne.work=function(){
alert(personOne.name+" is coding now...");
}
personOne.work();2.2)可以使用有參構造函數(shù)來實現(xiàn),這樣定義更方便,擴展性更強(推薦使用)
代碼如下
function Pet(name,age,hobby){
this.name=name; //this 作用域:當前對象
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert("我叫"+this.name+",我喜歡"+this.hobby+",也是個吃貨");
}
}
var maidou =new Pet("麥兜",5,"睡覺"); //實例化/創(chuàng)建對象
maidou.eat(); //調用 eat 方法(函數(shù))代碼如下:
var wcDog =new Object();
wcDog.name="旺財";
wcDog.age=3;
wcDog.work=function(){
alert("我是"+wcDog.name+",汪汪汪......");
}
wcDog.work();代碼如下:
function Dog(){
}
Dog.prototype.name="旺財";
Dog.prototype.eat=function(){
alert(this.name+"是個吃貨");
}
var wangcai =new Dog();
wangcai.eat();代碼如下:
function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype.sell=function(){
alert("我是"+this.name+",我現(xiàn)在賣"+this.price+"萬元");
}
var camry =new Car("凱美瑞",27);
camry.sell();代碼如下:
function Car(name,price){
this.name=name;
this.price=price;
if(typeof Car.sell=="undefined"){
Car.prototype.sell=function(){
alert("我是"+this.name+",我現(xiàn)在賣"+this.price+"萬元");
}
Car.sell=true;
}
}
var camry =new Car("凱美瑞",27);
camry.sell();以上幾種,是 javascript 中最常用的創(chuàng)建對象的方式

猜你喜歡:
JavaScript數(shù)據(jù)類型:javascript數(shù)據(jù)類型有哪些?