Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - What's the difference between this.function and prototype.function?

Given simple JS inheritance, what's the practical difference in the base function between these two examples? In other words, when should a person choose to define a function on "this" instead of on the prototype (or the other way around)?

For me the second example is easier to digest, but how much more is there to this?

function defined on this:

//base
var _base = function () {
    this.baseFunction = function () {
        console.log("Hello from base function");
    }
};
//inherit from base
function _ctor() {
    this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);

function defined on prototype:

//base
var _base = function () {};
_base.prototype.baseFunction = function () {
    console.log("Hello from base function");
}
//inherit from base
function _ctor() {
    this.property1 = "my property value";
};
_ctor.prototype = new _base();
_ctor.prototype.constructor = _ctor;
//get an instance
var instance = new _ctor();
console.log(instance.baseFunction);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Functions on the prototype are only created once and shared between each instance. Functions created in the constructor are created as new objects for each new object created with the constructor.

As a general rule functions should be on the prototype since they will generally not be modified for different objects of the same type, and this has a slight memory/performance benefit. Other properties like objects and arrays should be defined in the constructor, unless you want to create a shared, static property, in which case you should use the prototype.

Its easier to see the distinctions with normal objects or arrays rather than functions

function Foo(){
    this.bar = [];
}
var fooObj1 = new Foo();
var fooObj2 = new Foo();

fooObj1.bar.push("x");
alert(fooObj2.bar) //[]

as opposed to:

function Foo(){
}

Foo.prototype.bar = []
var fooObj1 = new Foo();
var fooObj2 = new Foo();

fooObj1.bar.push("x");
alert(fooObj2.bar) //["x"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...