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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM