Difference between prototype and this in JavaScript

来源:互联网 发布:centos 查看软件版本 编辑:程序博客网 时间:2024/04/30 10:15

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

AABA

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

AABB

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

CCCC

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