关于你的观点:
- 肯定会提高性能,尤其是在函数方面 - 在原型上声明函数要好得多。
- 我认为您的意思是说“公共”属性,以便通过编写
some_instance.foo 来检索信息。 “静态”属性/方法不同(见下文)。
- 正确。继承只能从原型中真正发生。
让我解释一些事情,看看这是否有帮助。在 javascript 中创建新的“类”是一个相当简单的过程。
var MyClass = new Function();
此时,引擎知道您的新类,并在创建“类”的新实例时知道“要做什么”(就性能而言)。
var my_instance = new MyClass();
如果您想修改原型,您可以这样做并且知道每个实例都将得到更新,因为它们都共享相同的原型。
MyClass.prototype.name = "default name";
console.log( my_instance.name ); //=> default name
现在引擎知道有一个“名称”属性需要一个字符串值...它将这些资源分配给您的类的所有新实例和现有实例...这非常便利。请注意,像这样修改现有“类”的原型是一个昂贵的过程,不应频繁执行(但也不要害怕这样做)。
我不能真正谈论在实例上声明临时属性/方法的性能利弊:
my_instance.foo = function() { /* this is not in the prototype chain */ };
我的猜测是,这对引擎来说非常简单,除非您同时对数以万计的对象执行此操作,否则没什么大不了的。
使用原型 IMO 的主要好处是您可以编写代码来扩展方法的功能,并且知道您的“类”的所有实例都会相应地更新:
var old_foo = MyClass.prototype.foo;
MyClass.prototype.foo = function() {
/* new business logic here */
// now call the original method.
old_foo.apply(this, arguments);
};
关于“静态”属性,您可以在“类”(构造函数)本身上声明它们:
// example static property
MyClass.num_instances = 0;
现在您可以像这样创建 init/destroy 方法:
MyClass.prototype.init = function() {
this.constructor.num_instances++;
};
MyClass.prototype.destroy = function() {
this.constructor.num_instances--;
};
// and call the init method any time you create a new instance
my_instance.init();
console.log( MyClass.num_instances ); //=> 1
var instance_2 = new MyClass();
instance_2.init();
console.log( MyClass.num_instances ); //=> 2
instance_2.destroy();
console.log( MyClass.num_instances ); //=> 1
希望对您有所帮助。