繁体   English   中英

关于Javascripts Prototype的几个问题

[英]A few questions about Javascripts Prototype

我从经典的OOP背景来看Javascript并且在理解原型方面遇到了麻烦。

给出下面的代码示例:

  1. 我如何在foo中调用/执行bar?
  2. 为什么要使用“特权”功能而不是把它放在原型上?
  3. 这可能在第一季回答,但bar1和bar2可以互相呼叫吗?

     function foo() { this.property = "I'm a property"; this.privileged = function() { // do stuff } } foo.prototype.bar = function() { // do stuff } foo.prototype.bar2 = function() { // stuff } 

到目前为止,有很多关于此的FUD。

1)。 用法简单:

var xxx = new foo();  // Create instance of object.
xxx.privileged();  // Calls the internal closure.
xxx.bar();  // First looks for internals, then looks to the prototype object.

2)。 这基本上创建了一个只能在实例上修改的闭包。 根本不是私有的(因为任何东西都可以通过对象实例与它交谈),而是函数的单个副本,其中对象的每个实例都获得该函数的新副本。 您可以更改函数本身,但不能全局更改它。 我不是这种创造方法的忠实粉丝。

3)。 是:

foo.prototype.bar = function(){
    this.bar2();
}

foo.prototype.bar2 = function(){
    this.bar();
}
// Although... NEVER do both.  You'll wind up in a circular chain.

为了启发,我为你建立了一个小提琴,它应该有助于展示如何调用它们: http//jsfiddle.net/7Y5QK/

1)frist是Clyde Lobo的答案:

var f = new foo();
f.bar();

2)在consturctor上写一个函数(特权),每个实例都会创建一个新的,如果在prototype上定义了一个方法,每个实例共享同一个prototype的方法:

var f1 = new foo(), // instance 1
    f2 = new foo(); // instance 2

f1.privileged === f2. privileged // -> false , every instance has different function
f1.bar === f2.bar // -> true, every instance share the some function

3)你可以bar' by this.bar()来调用bar' by bar2 ,代码如下:

function foo() {
   this.property = "I'm a property";

   this.privileged = function() {
      // do stuff
   };
}

foo.prototype.bar = function() { // defined a method bar
    alert('bar called');
    this.bar2(); // call bar2
};

foo.prototype.bar2 = function() { // defined a method bar2
    alert('bar2 called');
};

var f = new foo();
f.bar(); // alert 'bar called' and 'bar2 called'
f.bar2(); // alert 'bar2 called'
  1. 你可以通过执行this.bar();来执行foo中的bar this.bar(); 但它只有在你使用new foo();时才有效new foo(); 并且有一个继承自foo的对象。 否则,如果你只是调用foo(); this将指向全局对象。

  2. 它本质上是相同的,只有你给函数内部的继承对象提供的属性和方法才能访问你传递给foo任何参数。

  3. 是的,他们可以互相打电话,因为功能是“悬挂的”。 他们可以访问最近的外部作用域中的所有变量和对象,以及它们的功能上下文。

您的代码中确实存在语法错误。 在分配原型的地方,您没有创建函数。 你的意思是:

foo.prototype.bar = function() { /* ... */ };

你可以创建一个像foo的例子

var f = new foo();

然后调用f.bar()f.bar2()

大卫已经解释了第2点和第3点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM