Js object creation practices, js object Creation

Source: Internet
Author: User

Js object creation practices, js object Creation
1. Object tool Encapsulation



2. Factory Model
function createPerson(name,age,job){ var o = {name:name,age:age,job:job, sayName:function(){ alert(this.name); }}; return o; };var wyz1 = createPerson("wyz","30","female"); var wyz2 = createPerson("wyz2","30","male"); wyz1.sayName(); wyz2.sayName();




3. constructor mode this
function MathFunc(a,b){this.a = a;this.b = b;this.add = function(){return a+b;}}var add = new MathFunc(3,4);var sum = add.add();alert(sum);


4. Apply and call
function MathFunc(a,b){this.a = a;this.b = b;this.add = function(){return a+b;}}var myadd={};//MathFunc.call(myadd,31,4);MathFunc.apply(myadd,[31,4]);var sum = myadd.add();alert(sum);


5. Prototype Sharing Method
function MathFunc(a,b){this.a = a;this.b = b;MathFunc.prototype.add = function(){return a+b;}};var myadd= new MathFunc(3,4);var sum = myadd.add();alert(sum);



Js object creation Problems

Yes, the js object must exist in the dom element. Your first method is to retrieve the object in the function. Therefore, when you call this function, the object has already been created, the second method is to use js to retrieve the element before it is created, so the object will not be found. If you have to use the second method, you can use JS to retrieve all the page elements after they are created:

Windows. onLoad = function () {document. getElementById ("demo"). innerHTML = Date ();};

Or use the method in jquey to do the following:
$ (Document). ready (function () {$ ("# demo" example .html (Date ());

How to create objects in js

.... Objects in js are similar to those in java, but they cannot be constructed simply!
The usage is similar to that of java!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.