js create an object

 

1.    <script type="text/javascript"> 

2.        function createObject(name) 

3.        { 

4.            var object = new Object(); 

5.             

6.            object.name = name; 

7.             

8.            object.setName = function(name){ 

9.                object.name = name; 

10.           } 

11.            

12.           return object; 

13.       } 

14.        

15.       var obj1 = createObject("lisi"); 

16.       alert(obj1.name); 

17.       obj1.setName("zhaogongzuo"); 

18.       alert(obj1.name); 

19.        

20.   </script>

the last line in createObject method is the key. That is return object. As you see, in the createObject method, one object actually generate an new function object. This is not what we want. It is better that an new object has its' own properties, and all objects share the same method. So we move the inner method out, and link it to the createObject method.

 

1.    <script type="text/javascript"> 

2.        function createObject(name) 

3.        { 

4.            var object = new Object(); 

5.             

6.            object.name = name; 

7.             

8.            object.setName = setName; 

9.             

10.           return object; 

11.       } 

12.        

13.       function setName(name) 

14.       { 

15.           this.name = name 

16.       } 

17.        

18.       var obj1 = createObject("lisi"); 

19.       alert(obj1.name); 

20.       obj1.setName("zhaogongzuo"); 

21.       alert(obj1.name); 

22.        

23.   </script>

object.setName = setName. the right hand side can not add braces, since the name itself refer to instance, not method.

 

Or use function like class in java, at least to some extent,

 

1.    function Person(username) 

2.        { 

3.            this.username = username 

4.        } 

5.         

6.        var person1 = new Person("gongzuo"); 

7.         

8.        alert(person1.username)

when "new" quote, the function Person generate an object and return.

Add properties through prototype. However, for froptype, all objects share the same heap reference, so if you change one, the other change too.

 

1.    Person.prototype.age = 27; 

2.              

3.    alert(person1.age);

 

本文出自 “笨鳥先飛” 博客

You May Also Like