js的静态方法与实例方法

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

静态方法

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: ƒ}

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

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容