美文网首页
js的静态方法与实例方法

js的静态方法与实例方法

作者: 我有一个小小小小的梦想啊 | 来源:发表于2020-11-19 11:29 被阅读0次

百度到的很多内容都是类似这样的:

静态方法

function Afun(){}

Afun.sayA=function(){
  console.log("Hello World A!");
}

实例方法

function Bfun(){}

Bfun.prototype.sayB=function(){
  console.log("Hello World B!");
}

var b=new Bfun();

b.sayB();//输出Hello World B!

然后就很少有然后了,今天突然看到静态方法与实例方法这个词之后,于是有了这篇文章,让我们看看还有什么其他不同。

上边提到静态方法是直接通过属性添加的方法,实例方法是添加给实例化对象的方法。

function Afun(){}

Afun.sayA=function(){
  console.log("Hello World A!",this);
}
Afun.sayA() //输出Hello World A! ƒ Afun(){}


function Bfun(){}

Bfun.prototype.sayB=function(){
  console.log("Hello World B!",this);
}

var b=new Bfun();

b.sayB();//输出Hello World B! Bfun {}

不难看出,静态方法中的this指向的是构造函数本身,而实例方法中的this指向的是实例化对象。

function Bfun(){
  this.sayC=function(){
    console.log("Hello World C!",this)
  }
}

Bfun.sayA=function(){
  console.log("Hello World A!");
}

Bfun.prototype.sayB=function(){
  console.log("Hello World B!");
}

var b=new Bfun();
Bfun.sayB(); // Uncaught TypeError: Bfun.sayB is not a function
Bfun.sayC(); // Uncaught TypeError: Bfun.sayC is not a function
b.sayA(); //  Uncaught TypeError: b.sayA is not a function
b.sayC(); //  Hello World C! Bfun {sayC: ƒ}

这里要表达的是实例方法不能通过构造函数直接调用,而静态方法也不能通过实例调用。定义在构造函数内部的形式也是实例方法,表现与原型链添加的方式一致,但并不推荐这种写法。

此外如果是通过原型链进行的继承,那么也不会继承静态方法

有说法静态方法和实例方法对内存的分配也不同,如果实例方法是通过原型链添加的话,我觉得没啥不同(手动狗头)。还望指教。

相关文章

网友评论

      本文标题:js的静态方法与实例方法

      本文链接:https://www.haomeiwen.com/subject/boskiktx.html