Javascript 什么';What’this.bla与Object.prototype.bla的区别是什么
假设我有以下代码:Javascript 什么';What’this.bla与Object.prototype.bla的区别是什么,javascript,function,this,prototype,Javascript,Function,This,Prototype,假设我有以下代码: (function(global) { function Bar(foo) { this.foo = foo; return this; } Bar.prototype.getFoo = function() { return this.foo; }; Bar.prototype.setFoo = function(val) { return (this.foo = v
(function(global) {
function Bar(foo) {
this.foo = foo;
return this;
}
Bar.prototype.getFoo = function() {
return this.foo;
};
Bar.prototype.setFoo = function(val) {
return (this.foo = val);
};
})(this);
使用prototype
创建像setFoo
这样的函数与这样做有什么区别:
function Bar(foo) {
this.getFoo = function() {
return this.foo;
};
}
function Crazy(name)
{
this.name = name;
this.callMe = function() {
return "Where are you " + this.name;
};
}
Crazy.prototype.callMe = function() {
return this.name + " come here";
};
var inst = new Crazy("Robert");
inst.callMe(); // "Where are you Robert"
delete inst.callMe;
inst.callMe(); // "Robert come here"
我知道什么是prototype,它意味着什么,我只是不明白为什么有些人会用prototype分配函数,因为如果我用prototype分配函数,每次我创建一个新的Bar实例时,它们都会可用。如果“类”有多个实例(松散地使用术语),它们都共享同一个原型。因此,附加在那里的东西更轻,并且它保证它们都有相同的版本(如果你想要的话) 将其视为实例字段与类字段
原型也可以链接以允许字段的“继承”。当您使用
原型时,该函数是共享的,当您将该函数分配给此
时,它们不是。相反,每个实例都有自己的函数副本。快速答案=函数共享+更小的内存占用
当您使用prototype.functionName
时,所有实例共享相同的函数(内存中只有一个副本),但如果您在构造函数中使用此.functionName
,则每个实例都有自己的相同函数副本(内存中存在多次)
使用prototype
有两个含义:
内存占用-如前所述
原型上的后续功能更改反映在所有现有(当然也包括未来)实例上——很少有人愿意这样做,但有人可以使用它
高级-两者都可以
您还可以同时拥有这两种功能,在这种情况下,本地副本优先于原型,这意味着您可以执行以下操作:
function Bar(foo) {
this.getFoo = function() {
return this.foo;
};
}
function Crazy(name)
{
this.name = name;
this.callMe = function() {
return "Where are you " + this.name;
};
}
Crazy.prototype.callMe = function() {
return this.name + " come here";
};
var inst = new Crazy("Robert");
inst.callMe(); // "Where are you Robert"
delete inst.callMe;
inst.callMe(); // "Robert come here"
旁白:
在原型继承中,自己的属性和继承的属性之间有着根本的区别
有时这可能非常相关
一个常用的经典for循环,只检查“自己的属性”,形式如下:
for (prop in array) {
if (array.hasOwnProperty(prop)) {
dostuff
}
当分配给此
时,所有属性都是自己的属性,使得hasOwnProperty检查不相关。您可以按照条
的每个实例创建单独的函数。原型方法,它只为所有实例创建一个函数。它可以节省内存。