javascript - 使用 this 和 prototype 在 JavaScript 中定义类的方法有什么区别?

标签 javascript oop prototypejs prototype-programming

<分区>

Possible Duplicate:
Javascript - this Vs. prototype
Advantages of using prototype, vs defining methods straight in the constructor?
Prototype or inline, what is the difference?

在 JavaScript 中创建类时,使用 this 在对象内部声明方法与通过访问 prototype 声明方法有何不同?在我看来,目的相同。

window.onload = function() { 
    tc = new TestClass();
    tc.init(); //logs initting
    tc.reset(); //logs resetting
    tc.doSomething(); //logs doing something
};


var TestClass = function(){

    this.init = function(){
        console.log("initting");
    }

    this.reset = function(){
        console.log("resetting");
    }

    this.destroy = function(){
        console.log("destroying");
    }

}

TestClass.prototype.doSomething = function(){

    console.log("doing something");
}

最佳答案

在大多数情况下,您会得到相同的功能结果。但在内部,它是完全不同的,因为当您将函数附加到 this 时,该类型的每个实例都会获得它自己的函数副本。通过将函数附加到 prototype,所有实例共享相同的函数实例。使用原型(prototype)可减少内存使用量。

关于javascript - 使用 this 和 prototype 在 JavaScript 中定义类的方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802900/

相关文章:

javascript - 导航网格寻路(多边形)

c++ - 基于策略的模板设计 : How to access certain policies of the class?

javascript - 使用循环在事件监听器上传递参数

javascript - 阻止 javascript 原型(prototype)设计杀死 for 循环

javascript - JQuery 与 YUI 比较?也许原型(prototype)?

javascript - JQuery 控制按钮单击时的 Popup div

javascript - 将 "min.js"文件放入 MVC 包中是否有意义?

javascript - 为 JS 中的函数添加属性

php - 在 Codeigniter 中重用表单和 Controller

java - 制作不可修改的对象