JavaScript原型与实践中的对比

JavaScript prototype vs. this in practice

本文关键字:实践中 原型 JavaScript      更新时间:2024-01-22

我在Stack Overflow和其他网站上读到了许多问题,这些问题都有有效且可理解的答案,我想我已经理解了使用JavaScript制作面向对象应用程序所需的一切,除了一件事:在this上使用类"prototype"的实际目的是什么?

  • 我已经读到,任何方法,即使是一个设置为this成员的方法,都将从构造函数(类)函数中调用,而不是为每个实例重新创建
  • 我见过许多使用prototype设置方法的例子,这意味着它将通过在实例上使用原始类函数的方法而不是全新的属性来节省内存

因此,除了指出上面两个选项中的哪一个是真的之外,我还想知道:prototype方法是访问构造函数的this("public")变量还是实例的(可能已设置为与构造函数不同)?

编辑-在构造函数的作用域内使用this.prototype.method = function()是错误的吗?我看到的所有例子都在函数创建后设置了一个原型方法

我将通过示例来回答您关于原型方法和this之间关系的问题。

来自moz文档:

如果该方法位于对象的原型链上,则this引用对象上调用该方法,就好像该方法在对象上一样。

示例:

// Our constructor function
function Example() {
    this.publicGreet = "Hello World";
};
// Here the function is set as a property of the constructors prototype
Example.prototype.greet = function() {
    alert(this.publicGreet);
};
// This creates a new object and invokes the constructor function
// Sets publicGreet as a property of that object and assigns it the value "Hello World"
var exampleInstance = new Example();
// Looks up the prototype chain and invokes it as a method of exampleInstance
// Remember our definition of `this` for methods on the prototype chain?
// Hence, `this` refers to exampleInstance, therefore `this.publicGreet` is "Hello World"
exampleInstance.greet();

此测试应解释性能问题:http://jsperf.com/prototype-vs-instance-functions/6

但是的,原型节省了内存,因为定义了一个回调,实例只指向这个回调。不需要声明同一回调的一堆副本。

访问问题:this.prototype中函数内声明的"this"指的是实例的"this":http://jsfiddle.net/pHtjK/

var b = Function;
b.prototype.a = function(){alert(this.b);};
var xyz = new b();
b.b = 'what';
b.a();