js中“函数的四种方法“,以及“类的三种方法“

在线地址

http://js.jsrun.net/66bKp/edit

参考https://blog.csdn.net/Stars_in_rain/article/details/107248637并做了修正

【函数】中四种方法:

1.内部方法(类似私有方法,因为我很少见到这种叫法,所以此处用类似):

定义在函数内部的方法,内部方法只能被内部的方法调用。

2.实例方法(也叫对象方法):

在构造函数中this指向的是他的实例对象,函数定义时,定义函数中最外层this上方法便是实例方法,只有实例才能调用。

3.原型方法:

在prototype上添加的方法,既可以通过构造函数的原型链去调用,

也可以实例去调用

4.静态方法(也叫类方法):

是直接在构造函数上定义的方法,不能被实例调用,构造函数可以调用

//js中函数的四种方法
function Father(){
    console.log("创建了一个实例")

    function neibu(){
        console.log("~~我是Father函数的【内部方法】") 
    }


    this.shili2 = function(){         
        console.log("~~我是Father函数的【实例方法/对象方法】(写法2)");
    }

    console.log("===下面打印函数中的this对象:");
    console.log(this); //this上有实例方法
    console.log("------------");
	neibu(); 
    
}


Father.prototype.yuanxing2 = function(){
    console.log("~~我是Father函数的【原型方法】(写法2)");
}


Father.jingtai2 = function(){
    console.log("~~我是Father函数的【静态方法/类方法】(写法2)");
}


let fa = new Father();
console.log("下面打印原型链:"); 
console.log(Father.prototype);//原型链上有原型方法
console.log("------------");
fa.yuanxing2(); //[用法1]用一个实例去调用
Father.prototype.yuanxing2()//[用法2]通过原型链调用
Father.jingtai2();
fa.shili2();

【类】中三种方法:

1.实例方法(也叫对象方法)

定义在构造函数constructor中的this对象上

2.原型方法

直接写在类中的方法,与constructor方法同级

3.静态方法(也叫类方法)

通过static关键字定义。

class Demo{
    //类中,构造函数里的this指向的是他的实例对象
    constructor(){
        this.shili1=()=>{//需要实例对象来调用
        console.log("~~类中的【实例方法/对象方法】(写法1)");
        }
    }
    static jingtai1(){
        console.log("~~类中的【静态方法/类方法】(写法1)");
    } 

    yuanxing1(){//【特别注意】这儿的是原型方法
        console.log("~~类中的【原型方法】(写法1)") 
    }

}

let demo = new Demo();
Demo.jingtai1();
demo.shili1()
demo.yuanxing1()//通过实例调用
Demo.prototype.yuanxing1()//通过原型调用

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

devwolf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值