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'
  • 相关阅读:
    弹出窗口的几种方法
    FCKeditor2.2+ASP.NET2.0不完全攻略
    如何运用 Form 表单认证 ?
    DataGrid的多种格式化显示方法
    如何显示在线人数,和所在位置?? [转自作者:子扬]
    备份和恢复Active Directory
    如何在vs.net里调试脚本 《一》
    初学ASP.Net时一些备忘的东西
    ASP.NET在线用户列表精确版——解决用户意外退出在线列表无法及时更新问题
    小技巧(一)分离字符串string str="(1,10,100,1000,10000,)";
  • 原文地址:https://www.cnblogs.com/ltchronus/p/2607355.html
Copyright © 2011-2022 走看看