javascript和java、c#等语言一样也具有面向对象的一些特征,但细比较的时候,会发现这些特征并不是真正的面向对象,很多地方都是利用对象本身来模拟面向对象,所以认为javascript不能算是面向对象编程语言,而是基于对象的语言。
在javascript中真的是万物皆对象,new出来的东西是对象,方法是对象,连类也都是对象。下面分别来看一下对象、方法和类的对象特征。
1.拿内置的date来看一下吧
复制代码 代码如下:
var time = new date();
var timestring = time.getfullyear() + - +
time.getmonth() + - +
time.getdate() + +
time.gethours() + : +
time.getminutes() + : +
time.getseconds();
document.write(timestring);
通过 time来操作其所引用的date对象,可以方便的调用date的对象所包含的一系列getxx()方法来获取年月日时分秒等信息。
可以再看一下string
复制代码 代码如下:
var username = new string(hello world);
document.write(username.length);
变量username引用了new出来的字符串对象,通过username访问字符串对象的length属性。
2.方法也是对象
复制代码 代码如下:
function hello() {
alert(hello);
};
var helloref = hello;
helloref();
hello是一个方法,helloref是一个引用了hello方法的变量,helloref和hello一样都指向了相同的方法对象。也就意味着helloref也可以执行,helloref()。同理也可以写出以下代码。
复制代码 代码如下:
var helloref = function() {
alert(hello);
};
helloref();
function(){alert(“hello”)}是一个匿名方法,当然也是对象,用helloref变量引用该方法对象后,可以通过helloref来调用方法。
3.那么类呢?当然类也是对象,在javascript中,不像c#或java那样有class关键字用来创建类,而是直接使用方法的关键字来创建类或者叫模拟类。
复制代码 代码如下:
function person(username, age) {
this.name = username;
this.age = age;
this.introduce = function() {
alert(我叫 + this.name + ,今年 + this.age + 岁了。);
};
};
var person1 = new person(张三, 20);
person1.introduce();
以上创建了一个person类型,person带有构造参数username和age,通过创建的person对象可以调用person所包含的方法introduce。下面对代码做一些修改。
复制代码 代码如下:
function person(username, age) {
this.name = username;
this.age = age;
this.introduce = function() {
alert(我叫 + this.name + ,今年 + this.age + 岁了。);
};
};
var personclass = person;
var person1 = new personclass(张三, 20);
person1.introduce();
重新声明新的变量personclass并引用person类,personclass和person都指向了原来的person所引用的类,所以也可以用personclass来创建对象。
以上的几个例子可能不是很恰当,但也可以一窥javascript中万物皆对象。
下一节详细的谈一谈javascript中的对象。
