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

it2023-02-28  93

在线地址

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()//通过原型调用

 

最新回复(0)