gpt4 book ai didi

javascript - this.function 和prototype.function 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 03:09:18 24 4
gpt4 key购买 nike

考虑到简单的 JS 继承,这两个示例之间的基本函数有什么实际区别?换句话说,什么时候人们应该选择在“this”上而不是在原型(prototype)上(或相反)定义函数?

对我来说,第二个例子更容易理解,但是还有多少呢?

在此定义的函数:

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

原型(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);

最佳答案

原型(prototype)上的函数仅创建一次并在每个实例之间共享。对于使用构造函数创建的每个新对象,构造函数中创建的函数将被创建为新对象。

作为一般规则,函数应该位于原型(prototype)上,因为它们通常不会针对同一类型的不同对象进行修改,这会带来轻微的内存/性能优势。其他属性(例如对象和数组)应在构造函数中定义,除非您想创建共享的静态属性,在这种情况下您应该使用原型(prototype)。

与普通对象或数组相比,更容易看出与函数的区别

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"]

关于javascript - this.function 和prototype.function 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com