JavaScript 原型(prototype)与实践中的 this

标签 javascript oop

我已经在 Stack Overflow 和网络上的其他网站上阅读了很多问题,并给出了有效且易于理解的答案,我想我理解了使用 JavaScript 制作面向对象应用程序所需的一切,除了一件事:什么是在 this 上使用类的 prototype 的真实、实际目的?

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

所以,除了评论上面两个选项中哪一个是正确的,我想知道:是一个 prototype 方法访问构造函数的 this ("public") 变量或实例的(可能已设置为不同于构造函数的)?

编辑 - 在构造函数的范围内使用 this.prototype.method = function() 是错误的吗?我见过的所有示例都在创建函数后设置原型(prototype)方法。

最佳答案

我将尝试通过示例回答您有关原型(prototype)方法与 this 之间关系的问题。

来自moz docs :

If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

示例:

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

关于JavaScript 原型(prototype)与实践中的 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303763/

相关文章:

c# - `CallVirt` 和 `New` 关键字

java - 这个叫什么?这是设计模式还是约定? (接口(interface)/类)

java - OOP:将设置传递给 Builder 类

javascript - vue中子循环中绑定(bind)数据与模型的问题

javascript - 基础导航顶部栏不适用于 thymeleaf

javascript - 下拉菜单与其他导航项重叠

javascript - 这不应该工作吗? $.getScript ("alert.js");

javascript - JavaScript 是否有接口(interface)类型(例如 Java 的 'interface' )?

JavaScript 将数组推送到类原型(prototype)问题

javascript - jquery click 在 IE 上未触发