zoukankan      html  css  js  c++  java
  • JavaScript: The Good Parts 学习随笔(四)

    Chapter 4. Functions

    4.1函数对象

      对象有连到原型的隐藏连接,函数对象连接到Function.prototype。

      函数在创建时带有prototype属性,它的值是一个有constructor属性且constructor的值就是函数值本身的对象。

    1 var func = function() {};//GC查看func的属性

    4.2函数字面量

    var add = function (a, b) {
        return a + b;
    };

    4.3调用

      javascript有四种调用函数的方式。调用函数时会传入两个参数this和arguments。

    4.3.1方法调用模式

      当函数作为一个对象的属性时叫方法。方法调用时this指向该对象。

    var myObject = {
        value: 0;
        increment: function (inc) {
            this.value += typeof inc === 'number' ? inc : 1;
        }
    };
    
    myObject.increment(  );
    document.writeln(myObject.value);    // 1
    
    myObject.increment(2);
    document.writeln(myObject.value);    // 3

    4.3.2函数调用模式

      当一个函数并非一个对象属性时,它被当作函数调用。

    var sum = add(3, 4);    // sum is 7

      这时this指向全局变量,需要靠一个变量来传值。

    // Augment myObject with a double method.
    
    myObject.double = function ( ) {
        var that = this;    // Workaround.
    
        var helper = function ( ) {
            that.value = add(that.value, that.value)
        };
    
        helper( );    // Invoke helper as a function.
    };
    
    // Invoke double as a method.
    
    myObject.double( );
    document.writeln(myObject.getValue( ));    // 6

    4.3.3构造器调用模式

      如果在函数前加个new,那么将创建一个连接到该函数prototype属性的新对象,同时this指向新对象。

    // Create a constructor function called Quo.
    // It makes an object with a status property.
    
    var Quo = function (string) {
        this.status = string;
    };
    
    // Give all instances of Quo a public method
    // called get_status.
    
    Quo.prototype.get_status = function (  ) {
        return this.status;
    };
    
    // Make an instance of Quo.
    
    var myQuo = new Quo("confused");
    
    document.writeln(myQuo.get_status(  ));  // confused

    4.3.4Apply模式调用

      其实就是apply函数的运用。

    // Make an array of 2 numbers and add them.
    
    var array = [3, 4];
    var sum = add.apply(null, array);    // sum is 7
    
    // Make an object with a status member.
    
    var statusObject = {
        status: 'A-OK'
    };
    
    // statusObject does not inherit from Quo.prototype,
    // but we can invoke the get_status method on
    // statusObject even though statusObject does not have
    // a get_status method.
    
    var status = Quo.prototype.get_status.apply(statusObject);
        // status is 'A-OK'
  • 相关阅读:
    Python 安装Twisted 提示python version 2.7 required,which was not found in the registry
    Openfire Strophe开发中文乱码问题
    css div 垂直居中
    How to create custom methods for use in spring security expression language annotations
    How to check “hasRole” in Java Code with Spring Security?
    Android 显示/隐藏 应用图标
    Android 当媒体变更后,通知其他应用重新扫描
    文件上传那些事儿
    专题:点滴Javascript
    主流动画实现方式总结
  • 原文地址:https://www.cnblogs.com/ltchronus/p/2607355.html
Copyright © 2011-2022 走看看