zoukankan      html  css  js  c++  java
  • JavaScript 静态方法和实例方法

    总结: 直接定义在构造函数上的方法和属性是静态的,  定义在构造函数的原型和实例上的方法和属性是非静态的

    静态方法:

    function ClassA(){ //定义构造函数
    };
    ClassA.func = function(){ //在构造函数上添加一个属性(因为函数也是对象)
        console.log("This is a static method");
    }
    var instance = new ClassA(); //新建一个实例
    ClassA.func(); //This is a static method
    instance.func(); //Error:instance.func is not a function
    

    非静态方法

    // 定义在构造函数原型上的方法是实例方法 
    function ClassA(){ //定义构造函数
    };
    ClassA.prototype.func = function(){ //在构造函数的原型上添加方法
        console.log("This is an instance method.");
    }
    var instance = new ClassA(); //新建一个实例
    ClassA.func();  // Error:ClassA.func is not a function
    instance.func(); //This is an instance method.
    
    // 定义在某个具体对象(实例)上的方法是实例方法
    function ClassA(){ //定义构造函数
    };
    var instance = new ClassA(); //新建一个实例
    instance.func = function(){
        console.log("This is an instance method.")
    }
    // ClassA.func();  // Error:ClassA.func is not a function
    instance.func(); //This is an instance method.
    

    可以在构造函数中直接为这个类所有对象绑定属性和方法

    function ClassA(){ //定义构造函数
        var method1 = function(){  //内部函数, 在外部不能访问 
            console.log("method1");
        }
        this.method2 = function(){ //为新创建的实例绑定方法
            console.log("method2");
            method1(); // 调用method1(),闭包使得method1()可以保存下来, 也就是说在构造函数调用之后还能继续使用.
        }
        this.method3 = function(){
            console.log("method3");
            this.method2(); // 调用对象已经绑定了的method2().
        }
    };
    
    var instance = new ClassA();
    instance.method3();
    
  • 相关阅读:
    【JavaWeb 实际项目 03】
    【JavaWeb EL表达式&JSTL标签库 09】
    【JavaWeb jsp 08】
    【JavaWeb 实际项目 02】
    【JavaWeb Servlet 07】
    【JavaWeb Servlet 06】
    【JavaWeb xml&tomcat 05】
    【JavaWeb jQuery 04】
    【JavaWeb jQuery 03】
    【JavaWeb JavaScript 02】
  • 原文地址:https://www.cnblogs.com/roger9567/p/5048276.html
Copyright © 2011-2022 走看看