惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
F
Fortinet All Blogs
Cloudbric
Cloudbric
P
Palo Alto Networks Blog
T
Threatpost
T
Tor Project blog
T
Tenable Blog
AWS News Blog
AWS News Blog
Project Zero
Project Zero
L
LangChain Blog
Cyberwarzone
Cyberwarzone
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
C
CERT Recently Published Vulnerability Notes
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Latest
Security Latest
云风的 BLOG
云风的 BLOG
I
Intezer
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
A
Arctic Wolf
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
MongoDB | Blog
MongoDB | Blog
aimingoo的专栏
aimingoo的专栏
K
Kaspersky official blog
Jina AI
Jina AI
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
D
DataBreaches.Net
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Secure Thoughts
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
MyScale Blog
MyScale Blog
IT之家
IT之家
Forbes - Security
Forbes - Security
The Hacker News
The Hacker News
Last Week in AI
Last Week in AI
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog

博客园 - DiviSoft

出如此错误,同样的代码却能在另一台机器执行(估计是补丁问题 - DiviSoft - 博客园 温习存储过程的CURSOR PHP下的DLL Accesss Denied解决之道 xp下的host文件配置 sqlserver in子句的使用?--如何实现CorpIDSet作为ID集合使用,能在存储过程中正确执行如一般SQL效果? 急:为什么我把本子置为 standby 待机 ,就唤不醒了呢(唤醒我的笔记本) php 安全介绍。。 j#操作EXCEL css 文本输出方式 采用textarea 转载:操作EXCEL .NET JDK在LINUX安装 js for myself 常用JS,HTML对象 smarty 模板 XML解析问题 php+cookies 使页面里所有大于_width的图片,全部成比例缩小成_width 崚 不能被 iconv(gb2312,utf-8 ,string) DOMDocument for php5
JavaScript类(转载)
DiviSoft · 2004-09-28 · via 博客园 - DiviSoft

Introduction

The article by Sergey Zavadski introduces the object model of the JavaScript programming language and demonstrates common practices in the OOP (object oriented programming) with JavaScript.

Simplicity of JavaScript.

JavaScript is proven to be one of the simplest programming languages to learn and use. A minor snippet of the code (in fact one string) performs various actions like creating of windows or changing the text in the status bar. The flexibility, short learning curve, and the fact that JavaScript is not a “strongly typed” language explains the extreme popularity of JavaScript among the web masters community which selected this language as the language of choice to provide static HTML pages with dynamic attractive content.

The powerful tool

However, in spite of its visible simplicity, the JavaScript, when following the DOM specifications, is quite an advanced and powerful tool providing all the required facilities for the creation of complex solutions (client side) such as menus, trees, grids etc. These possibilities are actually reflecting JavaScript’s power when it comes to the layers manipulations. Not the last reason for this power is the OOP structure of the JavaScript programming language which was planned and implemented as an object oriented language!

Object model

The JavaScript object is the entity with the properties that can be either other objects or variables. For example, we have Country_Italy object. We can assign the values to the properties of this object like this:

Country_Italy.Name=”Italy”;
Country_Italy.Capital=”Rome”;
Country_Italy.Area=301000;

However, the ‘Country_Italy’ object itself can be the property of another object:

Europe.MostBeautifulCountry= Country_Italy;

JavaScript comes with a library of built-in objects like Window, Math, String and many others. But what makes the language really flexible is the ability of creating custom objects. There are two possible methods for making custom objects in JavaScript. First one is using the direct initialization. The code in this case may look like this:

Country={Name:”France”,Capital:”Paris”,Government:{President:”Jacques Chirac”}};

We have created the Country object with ‘Name’, ‘Capital’ and ‘Government’ properties, and ‘Government’ property is an object with its own list of properties. We’ve also initialized these properties with initial values. All of this is done in one single string. The following construction creates and initializes the empty object:

Country={};

Another way to create objects in JavaScript is defining the special function constructor for the object and initialization of the object with the ‘new’ operator. For example:

function Country(Name,Capital,Population){
     this.Name=Name;
     this.Capital=Capital;
     this.Population=Population;
}

The ‘Country’ function is the constructor function. Now, to create the object using this defined constructor, we use the new operator:

Country_Italy=new Country(“Italy”,”Rome”,301000);

Just like in the previous example, the property can be the object itself:

function Government(President){
     this.President=President;
}
 
function Country(Name,Capital,Government){
     this.Name=Name;
     this.Capital=Capital;
     this.Government=Government;
}
Government_France=new Government(“Jacques Chirac”);
Country_France=new Country(“France”,”Paris”,Government_France);

Another advantage of the OOP fully implemented in JavaScript is that an object can have methods (not only properties). The methods are the functions described within an object scope that usually operate with the object’s properties. The methods are described much like the properties:

function describeCountry(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
           alert(desc);
}

In the above definition, this operator provides an access to the object the described method belongs to.

Country_Italy.describeCountry=describeCountry;

The construction below fully repeats the above one:

Country_Italy.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
     alert(desc);
}

The construction:

Country_Italy.describeCountry();

calls the ‘describeCountry’ method of the ‘Country_Italy’ object.

Prototypes based object oriented language

Unlike some other popular OO languages (Java, C++) whose object model is based on classes, the object model of JavaScript is based on prototypes. The main difference between those two approaches is that in a prototype based language, there’s no difference between the class and the class instance entities – you only deal with objects.

The prototype (can be viewed as a template that defines the way initial object’s property values are assigned) is any object declared with the prototype operator. This object can be the parent of any newly created object and this is how JavaScript supports inheritance – an important OOP language characteristic. Let’s see our Country object:

function Country(Name,Capital,Population){
      this.Name=Name;
      this.Capital=Capital;
      this.Population=Population;
}

Now, let’s declare ‘Cn’ - the ‘Country’ object prototype:

Cn=Country.prototype;

Cn.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
           alert(desc);
}

Now, we can call the ‘describeCountry’ method in any ‘Country’ descendant with only two strings of code:

Country_Italy=new Country(“Italy”,”Rome”,301000);
Country_Italy.describeCountry();

Using this approach, we can define in the prototype any number of methods and properties. Defining methods and properties in the prototype rather then defining them directly for each object gives many advantages:

  • You don’t have to define all required methods or properties every time the object is designed. You define all the necessary methods and properties in the prototype and then all you have to do is to create the object.
  • Makes your code more secure since you can keep all object definitions in a separate file.
  • Makes your code easier to read.

Inheritance

JavaScript also supports the inheritance mechanism that is the corner-stone of OOP.

To show the easiness of JavaScript inheritance mechanism, let’s review two already defined objects of ours: ‘Country’ and ‘Government’, and one new object ‘Parliament’.

Constructor functions for these objects will look like these:

function Country(Name,Capital,Population){
     this.Name=Name;
           this.Capital=Capital;
     this.Population=Population;
}
 
function Government(President){
     this.President=President;
}
 
function Parliament(Speaker){
     this.Speaker=Speaker;
}

Take a look at the ‘Country’ object prototype.

Cn=Country.prototype;
 
Cn.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
     alert(desc);
}

The following construction defines ‘Country’ as ‘Government’ prototype (‘Government’ inherits from ‘Country’):

Government.prototype=new Country("France","Paris",59330000);

When ‘Government’ object is created, it inherits all the ‘Country’ methods and properties. In other words, although ‘describeCountry()’ method is not defined for ‘Government’ object, it is available since ‘Country’ object is defined as ‘Government’ prototype.

Government_France=new Government("Jacques Chirac");
Government_France.describeCountry();

New methods can also be defined for the ‘Government_France’ object:

Government_France.describeGovernment=function(){
             alert(“President: ”+this.President);
}

Let’s complete the ‘Parliament’ object definitions.

Parliament.prototype=new Country("France","Paris",59330000);
 
Pn=Parliament.prototype;
Pn.describeParliament=function(){
     alert("Speaker: "+this.Speaker);
}

Parliament_France=new Parliament("Jean-Louis Debre");

As you can see, prototypes can also be modified for the inherited objects.

The above examples demonstrate elegance of the JavaScript OOP model which enables this easy to learn language to perform a variety of complex tasks for the real life programming.

Real life example

This very OOP approach was used in our company when we developed the CodeThat.Com’s set of web controls. For example, the ‘CodeThatCalendar’ is nothing but an object declared as:

 function CodeThatCalendar(def) {
     this.def = def;
     this.links = {};
     this.styles = {};
     this.hideifr = true;
           
     if (typeof(this.def.img_path)!="undefined") {
         if (this.def.img_path.lastIndexOf("\/")!=this.def.img_path.length-1)
             this.def.img_path=this.def.img_path+"\/";           
     }
             
     if (typeof(this.def.template_path)!="undefined") {
         if (this.def.template_path.lastIndexOf("/")!=
                       this.def.template_path.length-1) 
             this.def.template_path=this.def.template_path+"/";             
         if (this.def.template_path.indexOf("\/")!=0) 
             if (typeof(this.def.img_path)!="undefined" && 
                        this.def.img_path.indexOf("\/")!=0) {
                 s=this.def.template_path;
                   a=s.split("/");
                 a.length=a.length-1;
                 t="";
                 for (i=0; i<a.length; i++){
                     t=t+"../";
                 }
                 this.img_path=t+this.def.img_path;      
                 } 
         }
     };
 
var CTc = CodeThatCalendar.prototype;
 
CTc.hide = function()
     {
     …
     }
 
CTc.create = function(d,ctl) {
           …
    }

Various methods of the control work with the layers giving the control a fancy look and feel and enabling users to perform various actions the calendar is supposed to do. For example, the below function sets the value of the HTML form control to the date the user has selected. This is performed each time the user clicks the calendar date.

function CodeThatSetDay(c,f,d,m,y,i,ifr) {
     var doc;
     var w = window.opener||this.parent;
 
     if(w&&!i)
           doc = w.document;
     else
           doc = document;
     var e = CodeThatFind(doc,c);
     if(Def(e))
     {
           e.value=CodeThatDateFormat(f,d,m,y);
           if(e.fireEvent) e.fireEvent("onchange");
           else {
            if(e.onchange) e.onchange();   
           }
     }
 
     if(w&&!i)                            
     {
 
           if(Def(w) && Def(ifr))
           {
                var iframe = CodeThatFind(doc,ifr);
                if(Def(iframe))
                     iframe.style.visibility = 'hidden';
                if(ua.opera6)
                {
                     var d = CodeThatFind(doc,"calendar_div");
                     if(Def(d))
                     d.style.visibility='hidden';
                }
           }
           else
           {
                window.close();
           }
     }
};

(The examples of CodeThatCalendar functions are not fully functional. They are listed here for illustrative purposes). As you can see, JavaScript is indeed a powerful and user friendly programming language with many abilities which help to create really complex and interesting solutions. Since the DOM model is supported by majority of modern browsers, you can be sure your solution will be accessible for the majority of users. Of course, there’s much more to learn in JavaScript: events, DOM, layers, and cross-browser portability is also not always that transparent but this is for another story or... several stories.