如何在使用构造函数进行原型设计时访问实例?

时间:2012-06-16 19:52:47

标签: javascript oop constructor prototype

我正在通过prototype方法扩展构造函数类的功能,但是我无法弄清楚如何访问即将成为构造函数类的实例。

假设我们有以下课程:

Bla = function()
{
    this.a = 5;
}

足够简单。现在,我将用一种非常简单的方法扩展它......

Bla.prototype.f = function(){console.log("Abdf.")};

new Bla().f(); //Logs "Abdf as expected."

但是,如果我想访问a属性(5)怎么办?假设我试图像这样扩展构造函数类:

Bla.prototype.f2 = function(b){return b * here_are_the_problems.a};

显然使用this指的是其他内容。我该怎么用?

2 个答案:

答案 0 :(得分:2)

使用this来引用调用该方法的对象...

console.log(this.a);

有几种方法可以设置this的值。一个是它通常是指在函数作为对象的方法被调用时调用函数的对象。

Bla = function()
{
    this.a = 5;
}


Bla.prototype.f = function(){console.log(this.a)};

var bla = new Bla();

bla.f(); //Logs 5

因此,您可以看到f被调用为Bla变量引用的bla实例的方法,this的值f将被设置为引用同一个对象。

答案 1 :(得分:2)

使用this关键字访问任何实例属性或方法。 this代表实例。由于a是实例属性,prototype方法是实例方法,因此可以在prototype中访问它。

Bla = function() {
    this.a = 5;
};
Bla.prototype.foo = function () {
   console.log( this.a );
}

var x = new Bla;
x.foo(); // logs 5
​

但是,如果我们直接将方法添加到Bla ...

Bla.bar = function () {
   console.log( this.a ); // ERRORRRRR
}

因为bar不是实例(prototype)方法。在这种情况下,它是static method Bla并且没有实例,this引用函数Bla.bar,在这种情况下没有属性{ {1}}