0

我有一个非常基本的 javascript 问题,我什至无法制作适当的 Google 查询来回答它。例如:

function Parent(name){
  this.name = name;
}

Parent.prototype.Child() = function (){
  if(this.name == 'Sam'){ // This is the comparison that obviously doesn't work
    /* Do something */
  } else {
   /* Do something else */
  }
}

var Parent1 = new Parent('Sam');
var Child1 = new Parent1.Child();

在比较中是否有一个关键字可以用来代替 this 来访问 Parent 的“name”属性?

干杯!

4

2 回答 2

1

这个例子不起作用,因为你有()它不属于的地方。它应该如下所示:

Parent.prototype.Child = ...

此外,在这条线上..

var Child1 =  new Parent1.Child();

...它应该是

var Child1 = Parent1.Child();

我们取出了new因为Parent1不是构造函数。

然后,您的代码将按照您的预期运行。

于 2012-08-25T22:50:49.573 回答
1
var Parent1= new Parent('sam')

这将创建一个名为 parent1 的对象

因为 parent1 有能力使用子功能

它应该是

Parent.prototype.Child = function (){ 

最后你可以使用这个

parent1.child()
于 2012-08-25T22:53:53.253 回答