search
HomeWeb Front-endJS Tutorialjavascript 面向对象编程 function也是类_js面向对象

但javascript中并没有类概念,所谓的类也是模拟而来,通过函数加闭包模拟出类成员及私有成员(关于闭包可以参见跨越边界: 闭包)。这里我们将用比较平实的方式来了解一下javascript中的”类”,避开一些生硬的原理。

      既然是用function来模拟类,所以编写代码创建类的关键字还是function。我们创建一个座标点类。

    <SPAN class=kwrd>function</SPAN> Point() {
      <span class="kwrd">this</span>.X = 0;
      <SPAN class=kwrd>this</SPAN>.Y = 0;
    };
 
    <span class="kwrd">var</span> zeroPoint = <span class="kwrd">new</span> Point();
    alert(<SPAN class=str>"当前座标值( X:"</SPAN> + zeroPoint.X + <SPAN class=str>" , Y:"</SPAN> + zeroPoint.Y + <SPAN class=str>" )"</SPAN>);

        image

      大家都知道非静态类成员的访问需要通过对象来完成,所以先new出了一个Point类型对象,再通过该对象完成X和Y轴座标值的访问。从语法上来说,javascript类对象的创建过程和C#等差不多,但实现机制却不相同。这里的new创建出了一个Object,后续的Point()函数执行时将其this指向了这个新的Object对象。Point中的this.X和this.Y是Point类的两个公共成员,所以Point的对象可以直接对它们进行访问。

      说到类成员或对象的成员,免不了要提到可访问性的问题。在javascript的类中,也有public成员和private成员之分,但究其细节却不尽相同。javascript私有成员也是些在类外部不可以通过对象进行操作的成员,其实在类的内部成员之间私有成员也不定能被访问。在类的内部一般只有私有成员和私有成员之间可以互相的访问,你可以认为其它成员权限不够不能操作这些隐私的东西,但如果你有特权,那就不一样了,管它私有公开照用不误。私有成员变量和普通变量声明一样,用var关键字,私有方法可以用var声明变量来接收方法对象,也可以像普通方法那样去构建。

    <SPAN class=kwrd>function</SPAN> Lady() {
      <span class="kwrd">var</span> age = 30;
      <SPAN class=kwrd>var</SPAN> name = <SPAN class=str>"菜花"</SPAN>;
 
      <SPAN class=kwrd>var</SPAN> think = <SPAN class=kwrd>function</SPAN>() {
        alert(<span class="str">"其实我今年"</span> + age + <span class="str">"岁。"</span>);
      };
      
      <SPAN class=kwrd>function</SPAN> fancy(){
        alert(<span class="str">"幻想变成20岁。"</span>);
      };
 
      <SPAN class=kwrd>this</SPAN>.Introduce = <SPAN class=kwrd>function</SPAN>() {
        alert(<span class="str">"我叫"</span> + name + <span class="str">" , 今年20岁。"</span>);
      };
    };
 
    <span class="kwrd">var</span> younglady = <span class="kwrd">new</span> Lady();
    alert(younglady.age);<SPAN class=rem>//结果undefined</SPAN>
    younglady.think(); <span class="rem">//不支持</span>
    younglady.fancy(); <SPAN class=rem>//不支持</SPAN>

      上面是一个Lady类,age、think、fancy都是私有成员,think和fancy方法可以访问age和name,think和fancy两个方法也可以互相进行调用。但它们是私有的,所以创建出来的youngLady对象并不能调用到age、think和fancy,当然也不能调用到name。如果私有成员只能互相之间调用,其实也就失去了私有成员存在的意义。javascript提供特权成员可以建立外界和私有成员互通的桥梁。特权成员是公共成员的一种,公共成员有普通公共成员、特权成员和对象公共成员。

      特权成员就是在类中用this.XX的方式建立的成员,它们可以通过对象来被调用,它们也可以访问私有成员,可以建立私有成员被访问的通道。

    <SPAN class=kwrd>function</SPAN> Lady() {
      <span class="kwrd">var</span> age = 30;
      <SPAN class=kwrd>this</SPAN>.Name = <SPAN class=str>"菜花"</SPAN>;
 
      <SPAN class=kwrd>var</SPAN> think = <SPAN class=kwrd>function</SPAN>() {
        alert(<span class="str">"其实我今年"</span> + age + <span class="str">"岁。"</span>);
      };
 
      <SPAN class=kwrd>function</SPAN> fancy() {
        alert(<span class="str">"幻想变成20岁。"</span>);
      };
 
      <SPAN class=kwrd>this</SPAN>.Introduce = <SPAN class=kwrd>function</SPAN>() {
        alert(<span class="str">"我叫"</span> + <span class="kwrd">this</span>.Name + <span class="str">" , 今年"</span> + age + <span class="str">"岁。"</span>);
      };
    };
 
    <span class="kwrd">var</span> younglady = <span class="kwrd">new</span> Lady();
    younglady.Introduce(); <SPAN class=rem>//Introduce</SPAN>

        image

      普通公共成员的创建,不在类的里面来编码,而是通过类的prototype来创建。添加普通公共成员都直接添加到类的prototype中,而prototype就是一个像JSON对象一样的成员集对象。当我们进行对象创建时,可以认为会将类prototype中的成员整体copy入新的Object对象中。

    <SPAN class=kwrd>var</SPAN> younglady = <SPAN class=kwrd>new</SPAN> Lady();
    younglady.Introduce(); <span class="rem">//Introduce</span>
 
    Lady.prototype.Hobby = <span class="str">"上网"</span>;
    Lady.prototype.GetName = <SPAN class=kwrd>function</SPAN>() {
      <span class="kwrd">return</span> <span class="kwrd">this</span>.Name;
    };
    
    <SPAN class=kwrd>var</SPAN> lady2 = <SPAN class=kwrd>new</SPAN> Lady();
    alert(lady2.GetName());
    alert(lady2.Hobby);

      上面代码通过prototype为Lady类添加了普通公共成员GetName方法和Hobby属性,因为是公共成员,所以它们可以和原先定意在类中的特权成员进行互相访问。因为公共成员可以互相访问。对上述代码做些修改。如下。

    <SPAN class=kwrd>var</SPAN> younglady = <SPAN class=kwrd>new</SPAN> Lady();
 
    Lady.prototype.Hobby = <SPAN class=str>"上网"</SPAN>;
    Lady.prototype.GetName = <span class="kwrd">function</span>() {
      <SPAN class=kwrd>return</SPAN> <SPAN class=kwrd>this</SPAN>.Name;
    };
 
    alert(younglady.GetName());
    alert(younglady.Hobby);

      先创建出Lady对象,再修改类成员,先前创建好的对象也具有了新的成员。这就是prototype做为类原型所带来的好处,这里简单理解,可以认为prototype是类对象的模版,模版的修改会影响到所有该类对象。

      在添加普通成员的时候也可以来个批量的添加,直接用一个新的JSON对象来赋给prototype就可以了。但是要注意,现在是将原先的prototype进行了替换,在替换之前创建的对象引用的是旧的prototype对象,所以对prototype替换之前创建的对象不会有Hobby和GetName成员。

    Lady.prototype = {
      Hobby: <span class="str">"上网"</span>,
      GetName: <SPAN class=kwrd>function</SPAN>() {
        <span class="kwrd">return</span> <span class="kwrd">this</span>.Name;
      }
    };
    <SPAN class=kwrd>var</SPAN> younglady = <SPAN class=kwrd>new</SPAN> Lady();
    alert(younglady.GetName());
    alert(younglady.Hobby);

      除了在构建类时可以添加公共成员,还可以对对象直接进行成员操作。这在本小系列第二篇文章里有描述。这里做一下补充,对对象直接添加的成员,也是一种公共成员,这些成员也可以和类中原先具有的公共成员进行访问。

    younglady.SetName = <SPAN class=kwrd>function</SPAN>(name) {
      <span class="kwrd">this</span>.Name = name;
    };
    younglady.SetName(<span class="str">"菜明"</span>);
    alert(younglady.GetName());

以上说了一下类成员的东西,下次再说说类继承相关的东西。(如有不当说法请指正)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.