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

發佈了72 篇原創文章 · 獲贊 14 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章