JavaScript Object-oriented programming _javascript techniques

Source: Internet
Author: User
Definition of Class

Method One: General definition method of class
function Player1 (_name)
{
THIS.name = _name;
This.say = function () {alert (this.name);};
}

var p1 = new Player1 (' llinzzi1 ');
P1.say ();


Method Two: Prototype definition method
var player2 = function () {}
Player2.prototype = {
Name: ',
Say:function () {
alert (this.name);
}
}

var P2 = new Player2 ();
P2.name = ' Llinzzi2 ';
P2.say ();


Method Three: The above method structure is beautiful, convenient, but the construction function cannot take the parameter, the modification method
var player3 = function () {
This.init.apply (this, arguments);
}
Player3.prototype = {
Init:function (_name) {
THIS.name = _name;
},
Say:function () {
alert (this.name);
}
}

var p3 = new Player3 (' Llinzzi3 ');
P3.say ();

Inheritance of Classes

Method One
var player4 = function () {
This.init.apply (this, arguments);
}
Player4.prototype = new Player3;
Player4.prototype.shout = function () {
Alert (This.name.toUpperCase ());
}

var P4 = new Player4 (' Llinzzi4 ');
P4.shout ();


Method Two The above method can not adopt the method of {}, modify the method
Object.extend = function (destination, source) {
For (Var property in Source)
Destination[property] = Source[property];
return destination;
};

var player5 = function () {
This.init.apply (this, arguments);
}
Object.extend (Object.extend (Player5.prototype,player3.prototype), {
Shout:function () {
Alert (This.name.toUpperCase ());
}

});

var P5 = new Player5 (' llinzzi5 ');
P5.shout ();




And then copy one end of the Prototype.js browser to determine the code

Browser = {
Ie:!! (Window.attachevent &&!window.opera),
Opera:!! Window.opera,
WebKit:navigator.userAgent.indexOf (' applewebkit/') >-1,
Gecko:navigator.userAgent.indexOf (' Gecko ') >-1 && navigator.userAgent.indexOf (' khtml ') = = 1,
Mobilesafari:!! Navigator.userAgent.match (/apple.*mobile.*safari/)
}

alert (Browser.mobilesafari);

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.