我有一个关于JavaScript的问题。我知道如何使用prototype,以及为什么使用它,但我试图回答这个问题,如果我在这样的函数中使用prototype会发生什么,
var Command = function () {
    var text = 'Hello World';
    Command.prototype.run = function () {
        console.log(text);
    };
};
var command = new Command();
command.run();现在我也可以使用私有函数或变量了。我有用原型构建的例子,所有的变体都有,它表明我在哪里使用jsFiddle似乎没有什么区别。但我是不是上锁了?
发布于 2015-11-04 21:09:29
如果在函数内部的函数原型上设置run()函数,则每次运行函数时都会重新定义该函数。
这是没有意义的(因为你可以只定义另一个函数,而不是设置原型),效率低下(因为你一遍又一遍地做相同的工作),另一个看着你的代码的开发人员不会理解你为什么要这样做,而你可以在函数之外定义它。
这就是为什么你看不到其他人这样做的原因。在原型上的函数外部定义run()只需定义一次。这是惯用的JS,例如。MDN。
我没有意识到这样做有任何技术上的问题。
发布于 2015-11-04 19:37:05
var表达式正在被函数表达式Command.prototype.run关闭。这称为闭包。
var Command = function () {
    var text = 'Hello World';
    Command.prototype.run = function () {  // text is closed over by this function
        console.log(text);
    };
};
Command.prototype.run1 = function () { // text is not in scope and thus not available.
    console.log(text);
};
var command = new Command();
command.run();  // this will work and display what is in text
command.run1();  // this will fail and throw text undefined error.通常,如果变量在定义函数的作用域中,则该变量将可用于该函数。如果不是,那么您将无法访问它。
发布于 2015-11-04 19:40:07
Prototype使用具有内存管理优势。如果你不使用prototype,当你创建新对象时,你将不得不用这个来创建新函数。
var Command = function () {
    var text = 'Hello World';
    //One time create this function
    Command.prototype.run = function () {
        console.log(text);
    };
     this.test= function(){
       console.log(text);
     }
};
var command = new Command(); //again created test function, because it doesn't have a prototype
command.run();
command.test();https://stackoverflow.com/questions/33520666
复制相似问题