Js中关于内部方法、实例方法、原型方法、静态方法的个人见解。

function foo(name){
    this.name=name;
    // 实例方法
    this.GetName=function(){
        console.log("my name is "+name);
        GetId();
    }
    // 内部方法
    var GetId = function(){
        console.log("I have no id..");
    }
}

// 类方法
foo.SayHi=function(){
    console.log("hi!");
}

// 原型方法
foo.prototype.SayBye=function(){
    console.log("bye!");
}

//测试
var xiaoming= new foo("xiaoming");
xiaoming.GetName();// 实例方法只能实例调用,内部方法只能被内部的方法调用
foo.SayHi();//静态方法只能被类调用
xiaoming.SayBye();//原型方法只能被实例调用

 

ES6------------------------------------------------------------------

https://www.runoob.com/w3cnote/es6-class.html

 

 

 

静态方法

class Example{ static sum(a, b) { console.log(a+b); } }                             Example.sum(1, 2); // 3

原型方法

class Example { sum(a, b) { console.log(a + b); } }                                   let exam = new Example(); exam.sum(1, 2); // 3

实例方法

class Example { constructor() { this.sum = (a, b) => { console.log(a + b); } } }

 

相关文章