Javascript - 原型(prototype)设计的值(value)是什么?

标签 javascript function class prototype

我一直在尝试了解原型(prototype)设计的应用,但我看不出它为整个 JS 添加了太多实用性。

首先,我可能应该介绍一下我对原型(prototype)设计的理解。附加到构造函数的是一个原型(prototype)对象,您可以向其添加函数。然后,这些适用于“类”的所有迭代。让我们看下面的例子:

function myCar(myColor, myPrice) {
    var whatAmI = "A car!"; //A private, static data member
    var price = myPrice; //A private, non-static data member
    this.color = myColor; //A public data member
    this.utility = "driving"; //A public, static data member
}

现在假设我想为其添加方法。我有几种方法可以做到这一点。一种选择是我可以将它放在构造函数中。

function myCar(myColor, myPrice) {
    var whatAmI = "A car!"; //A private, static data member
    var price = myPrice; //A private, non-static data member
    this.color = myColor; //A public data member
    this.utility = "driving"; //A public, static data member

    this.honk = function() {
        console.log("Beep");
    {
}

var car1 = new myCar("blue", 1000);
car1.honk(); //Works

另一种选择是我可以将其原型(prototype)化。

myCar.prototype.honk2 = function() {
    console.log("Beep");
}

car1.honk2(); //Also works

但是我为什么要这样做呢?如果我保持将所有方法保留在构造函数中的格式,我可以以非常相似的方式包含私有(private)方法,从而实现代码一致性!

function myCar(myColor, myPrice) {
    var whatAmI = "A car!"; //A private, static data member
    var price = myPrice; //A private, non-static data member
    this.color = myColor; //A public data member
    this.utility = "driving"; //A public, static data member

    this.honk = function() {
        console.log("Beep");
    }
    this.honkTwice = function() {
        superSecretTransform();
    }
    var superSecretTransform = function() {
        console.log("NOW I AM A JET"); //I can't access this directly!
    }
}

我处理 JavaScript 的方式是否存在根本性错误?我什么时候应该关心原型(prototype)允许的动态数据成员/方法声明?

最佳答案

如果您有一个循环调用一个函数(例如每一帧),并在其中创建一个new myCar,那么它将在每次调用中创建相同的函数。如果你把它放在构造函数之外,该函数将只被调用一次......这是一个很大的性能改进。

关于Javascript - 原型(prototype)设计的值(value)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22582866/

相关文章:

javascript - 如何将 <tr> 插入到 <table> 中(使用 PHP)

javascript - JQuery 计算子元素的宽度

javascript - AngularJS 搜索不起作用

python : extracting only the first element on a dictionary of list using functions

c - 以多维数组作为参数的函数原型(prototype)

javascript - Typescript:基于类创建接口(interface)

c++ - 通过赋值初始化类对象

javascript - 如何根据我们的要求自定义选择元素或如何将下拉列表转换为可验证的选择组件

javascript - Javascript语句中的误解

c++ - 编译器错误 : No appropriate default constructor avaible