javaScript--Object(1)

1>:所有自定义对象和内置对象都继承了Object的属性方法:
--属性:constructor
  var date=new Date(2009,05,10,20,20,20);
  if(date.constructor==Date)
   {
     document.writeln(date.getFullYear());
   } 

--区别valueOf()和toString()方法:
  toString():仅仅完成的是将内容转换成字符串
  valueOf():功能更为强大,可以将内容转换成我们所需要的JavaScript原生类型


--hasOwnProperty():
  使用它可以知道用户自定义的属性;此时已经除去了继承的属性。


--Constructor:
  1: 同其它语言的构造函数一样,构造函数用来初始化一个对象。
  2: 构造函数没有返回值,但是JavaScript允许构造函数返回一个对象值。

为了符合于一般语言对象的定义的习惯,很多人会使用如下方式定义:
function Person(name,age)
{
   this.name=name;
   this.age=age;
   this.showMessage=function()
   {
     document.writeln("Name: "+this.name+"Age: "+this.age);
   }
}
var person=new Person("A!sen",20);
person.showMessage();
使用以上方式定义,在每次用构造函数创建好对象对之后,被创建好的对象就拥有了构造函数中的所有属性。当多个对象被创建这样做的效率是很低的。且脚本时很占内存的。

为了解决这样的问题:我们都会想在我们需要时才使用到相应的属性就可以达到目的。
使用prototype原型对象,每一个函数都有一个原形对象构造函数也是这样的。
1:每一个对象也都会继承自本身的原形对象。
注意:有一种说法不准确,使用函数的prototype属性可以为对象添加额外的属性,而实际上添加到prototype添加的熟悉都可以被创建的对象所继承而这些属性并非对象本生所有。
如:
function Cuboid(len,wid,hei)
{
    this.len=len;
    this.wid=wid;
    this.hei=hei;
}
Cuboid.prototype.colume=function()
{
    return this.len*this.wid*this.hei;
}
var cuboid=  new Cuboid(10,10,10);
document.writeln(cuboid.colume());
document.writeln(cuboid.hasOwnProperty("len"));
document.writeln(cuboid.hasOwnProperty("colume"));//false 说明colume并不是cuboid本身的属性   
document.writeln("colume" in cuboid);
//true 说明colume确实拥有属性colume因此得到属性来自prototype

注意:没有十足的把握不应该使用prototype去扩充JavaScript核心对象,当然你是高手就得另当别论了。

2:看第二种情况(一般很少用的):
function Cuboid(len,wid,hei)
{
    this.len=len;
    this.wid=wid;
    this.hei=hei;
}
var cuboid=  new Cuboid(10,10,10);
//在调用方法前为对象添加一个方法是非常愚蠢的做法。
cuboid.volume=function()
{
   return this.len*this.wid*this.hei;
}
document.writeln(cuboid.volume());
//宁愿用对象调用方法,比将对象作为方法的参数传递给函数好
cuboid.colume=function(cub)
{
  return cub.len*cub.wid*cub.hei;
}
document.writeln(cuboid.colume({"len":12,"wid":12,"hei":12}));

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值