zoukankan      html  css  js  c++  java
  • 简单介绍Javascript匿名函数和面向对象编程

    忙里偷闲,简单介绍一下Javascript中匿名函数和闭包函数以及面向对象编程。首先简单介绍一下Javascript中的密名函数。

    在Javascript中函数有以下3中定义方式:

    1.最常用的定义方式:

    function functionVal(variable){
        return 3*variable;
    }
    View Code

    2.使用Function构造函数,将函数的参数和函数体内容作为字符串参数[不建议使用]:

    var objFunction=new Function('variable','return 3*variable');
    View Code

    3. 第3中定义方式

    var functionVal=function(variable){
        return 3*variable;
    }
    View Code

    第3中方式"="右边是个匿名的函数,定义完成之后将函数对象赋值给"="左边的变量。

    以上提到了匿名函数,接下来熟悉一下匿名函数的作用:

    匿名函数的最大作用就是可以创建闭包和命名空间,匿名函数的这两大特性决定着可以很好的使用function来实现Javascript面向对象的编程,如下代码演示如何使用匿名函数来实现私有成员和共有成员:

    (function($){
        var privateVal='This is a global private static variable';
        
        ///
        /// Global private menthod
        ///
        function privateFunction(varibale){
            alert('This is a global private function')
        
        }
        $.nameSpace=function(){
            alert('This is a new name space');
        };
        
        $.nameSpace.publicFunction(variable){
            alert('This is a public function');
        }
    }(jQuery))
    View Code

    与以上匿名函数定义很类似的一种Javascript使用方法如下:

    $(function(){
        alert('A new method call document ready function');
    })
    View Code

    该方法等同于:

    $(document).ready(function (){
        alert('A method call document ready function');
    })
    View Code
  • 相关阅读:
    roportional Rate Reduction (PRR)
    【C++11新特性】 nullptr关键字
    C++ 智能指针
    std::thread
    C++11 的 std::ref 用法
    for auto
    C++11右值引用与移动构造函数
    leetcode刷题笔记一百零六题 从中序与后序遍历序列构造二叉树
    leetcode刷题笔记一百零五题 从前序与中序遍历序列构造二叉树
    leetcode刷题笔记一百零四题 二叉树的最大深度
  • 原文地址:https://www.cnblogs.com/chengbing2011/p/4187317.html
Copyright © 2011-2022 走看看