Difference between prototype and this in JavaScript

Resume

When I’m studying JavaScript, I got a little bit confused while I first time look at function.prototype(Here, function points to a certain function, not Function). In this passage, we will see the difference between prototype and this.


this

First of all, we propose an example.

var func = function(){
    this.get = function(){console.log('A')};
}
func.prototype.updateGet = function(){
    this.get = function(){console.log('B')};
}

var func0 = new func(),
    func1 = new func();
func0.get();
func1.get();
func0.updateGet();
func0.get();
func1.get();

And the result will be

A
A
B
A

as we expected.
Because, when we invoke updateGet(), it has just updated the function get() in object func0. So that func1 will not be affected.


function.prototype

var func = function(){}
func.prototype.get = function(){console.log('A')};
func.prototype.updateGet = function(){
    func.prototype.get = function(){console.log('B')};
}

var func0 = new func(),
    func1 = new func();
func0.get();
func1.get();
func0.updateGet();
func0.get();
func1.get();

And the result will be

A
A
B
B

Because when we modify functions in func.prototype, it means that we modify every instance depends on function in prototype.
As prototype means the prototype of a function, I believe it’s pretty fair to do so.

Reference: http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript


this > function.prototype

Moreover, as I have tested, when we do

var func = function(){this.get = function(){console.log('C')};}//We define get() here.
func.prototype.get = function(){console.log('A')};
func.prototype.updateGet = function(){
    func.prototype.get = function(){console.log('B')};
}

var func0 = new func(),
    func1 = new func();
func0.get();
func1.get();
func0.updateGet();
func0.get();
func1.get();

It will return

C
C
C
C

which makes me consider that this has higher priority than function.prototype.


Function.prototype

As all function “inherit” from Function, when we add methods to Function.prototype, it will add a method to all functions.

Function.prototype.test = function(){
    return 10;
}
var func = function(){}
func.test();

Codes above will show

10

as we expected.


References

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值