javascript三种创建对象的方式

javascript是一种“基于prototype的面向对象语言“,与java有非常大的区别,无法通过类来创建对象。那么,既然是面象对象的,如何来创建对象呢?

一、通过”字面量“方式创建。

方法:将成员信息写到{}中,并赋值给一个变量,此时这个变量就是一个对象。
例如:

 var person = (name:'dongjc', work:function() {console.log('write coding')});  
如果{}中为空,则将创建一个空对象:

 var person = {} //创建空对象 

演示代码:
1 <script type="text/javascript">
2 var person = {
3     name: "dongjc",
4     age: 32,
5     Introduce: function () { alert("My name is " + this.name + ".I'm " + this.age); }
6 };
7 person.Introduce();  
8 </script>
 我们还可以给对象丰富成员信息。
  对象.成员名称 = 值;
  对象[成员名称] = 值;
也可以获取对象的成员信息。
  对象.成员名称;
  对象[成员名称];
1 <script type="text/javascript">
2     var person = {
3     name: "dongjc",
4     age: 32,
5     Introduce: function () { alert("My name is " + this.name + ".I'm " + this.age); }
6 };
7 person.worker = 'coding'; //丰富成员信息
8 </script>

二、通过”构造函数“方式创建。

 方法:

 var obj = new 函数名(); 

 这与通过类创建对象有本质的区别。通过该方法创建对象时,会自动执行该函数。这点类似于php通过创建对像时,会自动调用构造函数,因此该方法称为通过"构造函数“方式创建对象。

 1 <script type="text/javascript">
 2 function Person() {
 3     this.name = "dongjc";    //通过this关键字设置默认成员
 4     var worker = 'coding';    //没有this关键字,对象创建后,该变量为非成员
 5     this.age = 32;
 6     this.Introduce = function () {
 7         alert("My name is " + this.name + ".I'm " + this.age);
 8     };
 9     alert("My name is " + this.name + ".I'm " + this.age);
10 };
11 var person = new Person();
12 person.Introduce();
13 </script>

 

此代码一共会两次跳出对话框,原因在于创建对象是自动执行了该函数。

注意:this关键字的使用。这里的this与php中话法意思类似,指调用该函数的对象,这里指的是person。

 

三、通过object方式创建。

方法:先通过object构造器new一个对象,再往里丰富成员信息。

 var obj = new Object(); 

实例代码:

1 <script type="text/javascript">
2 var person = new Object();
3 person.name = "dongjc";
4 person.age = 32;
5 person.Introduce = function () {
6         alert("My name is " + this.name + ".I'm " + this.age);
7     };
8 person.Introduce();
9 </script>

 

 

 

posted @ 2016-02-03 14:00  dongjc  阅读(31523)  评论(0编辑  收藏  举报