原文:http://www.phpied.com/3-ways-to-define-a-javascript-class/
1. 使用函数
这可能是最普通的方法之一。先定义一个函数,然后用其他关键字创建一个对象。
function App(type){
this.type = type;
this.color = "red";
this.getInfo = getAppleInfo;
}
function getAppleInfo(){
return this.color + ' ' + this.type + ' apple';
}
var apple = new Apple('macintosh');
apple.color = "reddish";
alert(apple.getInfo());
1.1 在内部定义方法
function Apple(type){
this.type = type;
this.color = "red";
this.getInfo = function(){
return this.color + ' ' + this.type + ' apple';
};
}
2. 使用JSON
JSON即Javascript Object Notation。
var apple = {
type: 'macintosh',
color: 'red',
getInfo: function(){
return this.color + '' + this.type + ' apple';
}
};
用这种方法的话,你不需要也 不能创建类的实例,因为他已经存在了。直接拿来用就行了。
apple.color = 'reddish';
alert(apple.getInfo());
3. 使用函数创建单独的一个
此方法综合了上面的两个方法。你可以使用函数来定义单独的一个class。
var apple = new function(){
this.type = 'macintosh';
this.color = 'red';
this.getInfo = function(){
return this.color + '' + this.type + ' apple';
};
}
你会发现他和1.1十分类似,但是他使用对象的方法确和2很像。
apple.color = 'reddish';
alert(apple.getInfo());
本文介绍了三种定义JavaScript类的方法:使用函数、使用JSON以及使用函数创建单独的一个实例。这些方法各有特点,适合不同的应用场景。

718

被折叠的 条评论
为什么被折叠?



