this.function和prototype.function有什么区别? [英] What's the difference between this.function and prototype.function?

查看:175
本文介绍了this.function和prototype.function有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于简单的JS继承,这两个例子之间的基函数的实际区别是什么?换句话说,一个人什么时候应该选择在this上而不是在原型上(或者反过来)定义一个函数?

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?

在此定义的函数:

//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);

原型上定义的函数:

//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);


推荐答案

原型上的函数只创建一次并在每个实例。在构造函数中创建的函数将作为使用构造函数创建的每个新对象的新对象创建。

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) //[]

而不是:

function Foo(){
}

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

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

这篇关于this.function和prototype.function有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆