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!