search
HomeWeb Front-endJS Tutorialjavascript 面向对象编程 function是方法(函数)_js面向对象

好程序不是写给computer的,而是写给human的。遇到复杂功能,应该想着把它简化、组件化,把小功能封装成小组件,小功能块可以任意的组合得到千变万化的复杂功能。function就可以帮助我们把功能进行封装。那什么是封装呢。要我说,只要把具体实现给打包,对外提供调用接口那就是封装,方法也好、类也好就做了这些事。

      javascript中的function可以用来创建方法、也可以用来创建类,实际上我们可以认为是用function来模拟出的类(说到类一般都会要去了解闭包的知识)。还是先看一下方法吧。

       javascript函数分为有名函数、匿名函数和在匿名函数基础上延伸出来的立即执行函数。

       普通函数就是用function直接声明的有名函数。

    <SPAN class=kwrd>function</SPAN> Hello() {
      alert(<span class="str">"hello , everybody!"</span>);
    };
 
    Hello();
 
    <SPAN class=kwrd>function</SPAN> SayHelloTo(somebody) {
      alert(<span class="str">"hello , "</span> + somebody + <span class="str">"!"</span>);
    };
 
    SayHelloTo(<SPAN class=str>"张三"</SPAN>);

      上面分别创建了Hello和SayHelloTo方法。Hello不带有参数,直接通过Hello()来完成调用。SayHelloTo方法带有一个参数,向谁问候时需要知道是在问候谁。在调用SayHelloTo(“张三”)时要传入参数。这些代码和java、C#都没有什么太大区别。在方法重载上却有较大改变,javascript本身并不支持什么重载,一个方法名就对应一个方法。如果强制的写出多个同名方法,其实会出现先写的方法被覆盖掉的情况。

    <SPAN class=kwrd>function</SPAN> Hello() {
      alert(<span class="str">"hello , everybody!"</span>);
    };
 
    Hello();
 
    <SPAN class=kwrd>function</SPAN> Hello(somebody) {
      alert(<span class="str">"hello , "</span> + somebody + <span class="str">"!"</span>);
    };
 
    Hello(<SPAN class=str>"张三"</SPAN>);

 

               image image

      第一个Hello方法被覆盖掉,执行时直接调用Hello()则认为调用第二个Hello方法但没有传递参数值,所以弹出了undefined信息。调用Hello(“张三”)时很正常的完成执行。其实javascript也可以用一些直白的方式来完成重载。学过C#的人都会知道有个params关键字,通过它可以实现向方法传递不定个数的参数。我们可以通过对参数的信息做手动的判断也可以模拟出类似重载的效果。而在javascript中根本就不需要什么params关键字,就可以很自然的实现任意个数参数的传递。function中有个arguments属性,可以把它看成一个数组,它按传递进来的参数的顺序来保存所有的参数。也就是说我们在定义方法时可以不声明参数名。

    <SPAN class=kwrd>function</SPAN> ShowArguments() {
      <span class="kwrd">var</span> args = <span class="str">""</span>;
      <SPAN class=kwrd>for</SPAN> (<SPAN class=kwrd>var</SPAN> i = 0; i < arguments.length; i++) {
        args += arguments[i] + <span class="str">","</span>;
      };
      alert(args.substr(0, args.length - 1));
    };
 
    ShowArguments(1, 2, 3, 4, 5, 6, 7);

          image
      试着用argements来模拟一下重载。

    <SPAN class=kwrd>function</SPAN> Hello() {
      <span class="kwrd">if</span> (arguments.length == 0) {
        alert(<SPAN class=str>"hello , everybody!"</SPAN>);
      }
      <SPAN class=kwrd>else</SPAN> {
        alert(<span class="str">"hello , "</span> + arguments[0] + <span class="str">"!"</span>);
      };
    };
 
    Hello();
    Hello(<SPAN class=str>"张三"</SPAN>);

      基于参数个数不同的重载。

    <SPAN class=kwrd>function</SPAN> Increase(arg) {
      <span class="kwrd">if</span> (<span class="kwrd">typeof</span> arg == <span class="str">"undefined"</span>) {
        alert(<SPAN class=str>"请输入参数"</SPAN>);
      }
      <SPAN class=kwrd>if</SPAN> (<SPAN class=kwrd>typeof</SPAN> arg == <SPAN class=str>"string"</SPAN>) {
        alert(String.fromCharCode(arg.charCodeAt(0) + 1));
      }
      <span class="kwrd">if</span> (<span class="kwrd">typeof</span> arg == <span class="str">"number"</span>) {
        alert(arg + 1);
      }
    };
    Increase();
 
    Increase(<span class="str">"a"</span>);
    Increase(1);
      基于参数类型不同的重载。

      函数除了有名函数之外也可以是匿名函数,匿名函数就是没有名子的函数,不论函数有名还是没有名子,都是一个完整的函数对象。匿名函数还是用function来声明,但不用为它指定名称。其它的方面,比如参数等等和有名函数没什么区别。

    <SPAN class=kwrd>function</SPAN>() {
      ……
    };

      匿名函数一般可以满足临时的函数需求,不需要有变量对其进行引用(有名的函数可以认为是有变量引用的函数)。比如需要一个函数做为值对象做为参数传入方法、需要编程的方式为对象添加事件,用匿名函数都可以很好的完成。当然你也可以单独声明变量来引用某个匿名函数对象,这和普通有名函数就没什么区别了。

    <SPAN class=kwrd>function</SPAN> Each(array, fun) {
      <span class="kwrd">for</span> (<span class="kwrd">var</span> i = 0; i <pre class='brush:php;toolbar:false;'>        fun(array[i]);
      };
    };
    <span class="kwrd">var</span> nums = [1, 2, 3, 4, 5, 6, 7];
    Each(nums, <SPAN class=kwrd>function</SPAN>(arg) {
      alert(arg);
    });

      上面代码执行,依次输出数组中的元素。

    <SPAN class=rem>//在窗体加载时,在标题上显示当前时间</SPAN>
    window.onload = <span class="kwrd">function</span>() {
      document.title = <SPAN class=kwrd>new</SPAN> Date().toString();
    };
 
    <span class="rem">//也可以将匿名方法传入定时器中</span>
    setInterval(<SPAN class=kwrd>function</SPAN>() {
      document.title = <span class="kwrd">new</span> Date().toString();
    }, 1000);

      使用匿名函数绑定事件和进行定时操作。

    <SPAN class=kwrd>var</SPAN> Hello = <SPAN class=kwrd>function</SPAN>() {
      alert(<span class="str">"hello , everybody!"</span>);
    };

      如果将匿名函数赋给变量,那和有名的普通函数就没区别了。但不管是变量引用还是普通地有名函数,这样的函数在内存上都持久的占有一定资源。有时候我们只想执行一次大不必使用有引用的函数,直接执行匿名函数可能是最好的选择。把匿名函数包起来,加个括号执行,一切ok,这就是由匿名函数延伸出来的立即执行函数。

    (<SPAN class=kwrd>function</SPAN>() {
      alert(<span class="str">"hello , everybody!"</span>);
    })();
 
    (<SPAN class=kwrd>function</SPAN>(somebody) {
      alert(<span class="str">"hello , "</span> + somebody + <span class="str">"!"</span>);
    })(<SPAN class=str>"张三"</SPAN>);

      立即执行函数在做事件绑定,设置回调函数等方面往往会有意想不到的效果,可以解决诸如对象引用等问题。

    <SPAN class=kwrd>var</SPAN> student = {
      Name: <span class="str">"张三"</span>,
      Age: 20,
      Introduce: <span class="kwrd">function</span>() {
        alert(<SPAN class=str>"我叫"</SPAN> + <SPAN class=kwrd>this</SPAN>.Name + <SPAN class=str>",今年"</SPAN> + <SPAN class=kwrd>this</SPAN>.Age + <SPAN class=str>"岁了!"</SPAN>);
      } };
    window.onload = (<SPAN class=kwrd>function</SPAN>(obj) { <SPAN class=kwrd>return</SPAN> <SPAN class=kwrd>function</SPAN>() { obj.Introduce(); }; })(student);

      因为javascript中函数的这些特点加之它的对象的特征,我们还可以写出一些有functional意味的程序出来。其实javascript中function真的是老大。

    <SPAN class=kwrd>function</SPAN> Sum(fun, x) {
      <span class="kwrd">if</span> (x <pre class='brush:php;toolbar:false;'>        <SPAN class=kwrd>return</SPAN> 0;
      <span class="kwrd">return</span> fun(x) + Sum(fun, x - 1);
    };
  
    alert(Sum(<SPAN class=kwrd>function</SPAN>(i) { <SPAN class=kwrd>return</SPAN> i * i; }, 100));

      下面这又是什么呢?是方法吗?是类吗?

    <SPAN class=kwrd>function</SPAN> Point() {
      
    };

      先啰嗦到这,下次再看看类。

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
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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version