javascript

发现不是很习惯javascript这种弱类型+出错忽略的语言 抓狂

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定义的内容。抓狂

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值