发现不是很习惯javascript这种弱类型+出错忽略的语言
根据《head first javascript》里面的描述,上例中每个对象都持有一个sayHello方法,而getAge方法则是共有一个,而它们都可访问对象自身的属性。相对而言sayHello的方式白白浪费了存储空间。所以在实用中,应当使用类名.prototype.方法名定义对象的方法,类名.方法名定义类的方法。
![抓狂](http://static.blog.csdn.net/xheditor/xheditor_emot/default/crazy.gif)
1.javascript里对象/类的属性有2种,分别是类属性和对象属性;方法有3种,类方法,类持有的实例方法,和实例方法,代码如下:
function Cuties(name, year)
{
this.name = name;
this.birth = year;
this.sayHello = function()
{
if(this.name=="jerry") return "Hi, I'm the lucky jerry!";
else return " I'm the bad tom!";
}
}
Cuties.prototype.getAge = function()
{
alert(this.birth);
return 2011 - this.birth;
}
Cuties.getDescription = function()
{
return "we are the cuties;"
}
var cat = new Cuties("tom", "2006");
var rat = new Cuties("jerry", "2007");
document.write("<p>"+cat.sayHello()+"</p>");
document.write("<p>"+cat.getAge()+"</p>");
document.write("<p>"+rat.sayHello()+"</p>");
document.write("<p>"+rat.getAge()+"</p>");
document.write("<p>"+Cuties.getDescription()+"</p>");
根据《head first javascript》里面的描述,上例中每个对象都持有一个sayHello方法,而getAge方法则是共有一个,而它们都可访问对象自身的属性。相对而言sayHello的方式白白浪费了存储空间。所以在实用中,应当使用类名.prototype.方法名定义对象的方法,类名.方法名定义类的方法。
个人觉得sayHello这种方式的存在是因为js可以将function赋给var导致的。另外,上述代码调用方法处的()去掉,也全部可以执行,但是返回的是 = 后面包括function定义的内容。