有什么区别
var A = function () {
this.x = function () {
//do something
};
};
Run Code Online (Sandbox Code Playgroud)
和
var A = function () { };
A.prototype.x = function () {
//do something
};
Run Code Online (Sandbox Code Playgroud) 编辑2016年10月:请注意这个问题是在2012年提出的.每个月左右有人添加一个新的答案或评论反驳答案,但这样做没有意义,因为问题可能已经过时(记住,这是Gnome Javascript编写gnome-shell扩展,而不是浏览器的东西,这是非常具体的).
按照我之前关于如何在Javascript中进行子类化的问题,我正在创建一个超类的子类,如下所示:
function inherits(Child,Parent) {
var Tmp = function {};
Tmp.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}
/* Define subclass */
function Subclass() {
Superclass.apply(this,arguments);
/* other initialisation */
}
/* Set up inheritance */
inherits(Subclass,Superclass);
/* Add other methods */
Subclass.prototype.method1 = function ... // and so on.
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何使用这种语法在原型上定义一个setter/getter?
我曾经做过:
Subclass.prototype = {
__proto__: Superclass.prototype,
/* other methods here ... */
get myProperty() {
// code. …Run Code Online (Sandbox Code Playgroud) 在JavaScript中,我们有两种方法可以创建"类"并赋予它公共功能.
方法1:
function MyClass() {
var privateInstanceVariable = 'foo';
this.myFunc = function() { alert(privateInstanceVariable ); }
}
Run Code Online (Sandbox Code Playgroud)
方法2:
function MyClass() { }
MyClass.prototype.myFunc = function() {
alert("I can't use private instance variables. :(");
}
Run Code Online (Sandbox Code Playgroud)
我读了很多次,人们说使用方法2效率更高,因为所有实例共享相同的函数副本而不是每个实例都有自己的副本.通过原型定义函数有一个巨大的缺点 - 它使得无法拥有私有实例变量.
即使理论上,使用方法1给对象的每个实例赋予它自己的函数副本(因此使用更多的内存,更不用说分配所需的时间) - 实际上实际发生了什么?似乎优化Web浏览器可以很容易地识别这种非常常见的模式,并且实际上让对象的所有实例引用通过这些"构造函数"定义的相同函数副本.然后,如果稍后显式更改,它只能为实例提供自己的函数副本.
关于两者之间的性能差异的任何见解 - 或甚至更好的现实世界经验 - 都将非常有帮助.
在玩ES6之后,我真的开始喜欢新的语法和功能了,但我确实对类有疑问.
新的ES6类是旧原型模式的语法糖吗?或者幕后还有更多的事情发生在这里?即:
class Thing {
//... classy stuff
doStuff(){}
}
Run Code Online (Sandbox Code Playgroud)
vs:
var Thing = function() {
// ... setup stuff
};
Thing.prototype.doStuff = function() {}; // etc
Run Code Online (Sandbox Code Playgroud) 随着2015年6月ECMAScript 6的发布,引入了Javascript类语法.
这个语法:
class Polygon {
constructor(width, height) {
this.width = width;
this.height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
基本相同:
function Polygon(width, height) {
this.width = width;
this.height = height;
}
Run Code Online (Sandbox Code Playgroud)
那么使用类而不是传统函数有什么好处呢?在什么条件下我应该使用类而不是函数?