【问题标题】:Custom Classes - this vs prototype? [duplicate]自定义类 - 这与原型? [复制]
【发布时间】:2012-05-17 13:22:58
【问题描述】:

可能重复:
Advantages of using prototype, vs defining methods straight in the constructor?

在 JavaScript 中创建自定义类和公共方法时的最佳做法是什么,更重要的是……为什么?

使用 'this' 创建公共方法?

var myClass = function() {

    this.myVar = "this is my value";

    this.myFunc = function() {
        alert( this.myVar );
    };

    this.myFunc();
};

-或- 使用“原型”创建公共方法?

var myClass = function() {

    this.myFunc();
};

myClass.prototype = {

    myVar: "this is my value",

    myFunc: function() {
        alert( this.myVar );
    }

};

非常感谢!!!

【问题讨论】:

  • 这个问题每天至少被问一次...

标签: javascript oop prototype


【解决方案1】:

使用原型声明方法意味着该方法在任何时候都可用于该原型的实例,只要该实例是在声明方法之后创建的。

使用this.foo = function(){ ... }在构造函数中声明它意味着该方法仅在构造函数中声明它的点之后可用。

作为一个简单的例子,让我们看看命名函数和匿名函数。

下面,我们声明一个命名函数并调用它两次。请注意,即使第一次调用是在函数声明之前,该函数从第一次调用开始就可以正常执行:

foo();

function foo()
{
    alert("foo");
}

foo();

现在,我们将使用存储在变量中的匿名函数来代替命名函数:现在请注意,第一次调用会导致错误,因为此时 foo 未定义。

foo();

var foo = function()
{
    alert("foo");
}

foo();

原型以(概念上)类似的方式工作,当我们更改函数的原型时,我们会在创建该函数的实例之前影响它。所以以下工作正常:

function f ()
{
    this.bar();
}

f.prototype.bar = function()
{
    alert("bar");
};

var f1 = new f();

请注意,f.prototype.bar 是在我们调用它的行之后物理声明的。现在将其与this. ... 方法进行比较。以下按预期工作

function g()
{
    this.h = function(){
        alert("h");
    };

    this.h();
}

var g1 = new g();

虽然这不是因为我们在为其赋值之前尝试调用this.h

function g()
{
    this.h();

    this.h = function(){
        alert("h");
    };
}

var g2 = new g();

请注意,虽然影响函数原型仍然使用将匿名函数分配给原型属性的机制。这意味着即使使用原型方法,如果我们在向原型添加函数之前实例化原型的实例,也会出现错误。例如,以下工作正常:

function f ()
{
    this.bar();
}

f.prototype.bar = function()
{
    alert("bar");
};

var f1 = new f();

但是如果我们将赋值上方的var f1 = new f(); 移动到f.prototype.bar 我们会得到一个错误:

function f ()
{
    this.bar();
}

var f1 = new f();

f.prototype.bar = function()
{
    alert("bar");
};

【讨论】:

  • 非常感谢您的详细回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 2020-01-15
  • 2015-04-19
  • 1970-01-01
  • 2019-04-13
  • 2010-12-06
  • 1970-01-01
相关资源
最近更新 更多