js create an object

來源:互聯網
上載者:User

 

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);

 

本文出自 “笨鳥先飛” 部落格

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.