繁体   English   中英

尝试在JavaScript中使用工厂调用方法时变得不确定

[英]Getting undefined when trying to call a method using a factory in JavaScript

尝试通过Javscript中的工厂函数在继承中使用合成而不继承,并且未使用以下代码定义函数:

(dogIsCreated未定义)

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dog');
      dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('Ready');
    }
  }
}

var ted = dog().create();

如果有人能指出我正确的方向,那会很棒吗? 我使用的语法完全错误吗?

谢谢 :)

除了使用this关键字之外,还需要定义create()方法的作用域。

var dog = function dog(state) {
  return {
    create: function create() {
      console.log('Create the dog');
      this.dogIsCreated();
    },
    dogIsCreated: function dogIsCreated() {
      console.log('Ready');
    }
  }
}

此(dogIsCreated)不是全局函数。 使用dog对象创建的dogIsCreated函数。 这是object方法,因此您要在另一个(相同)object方法中调用此方法,因此我们可以使用“ this”来调用该方法–

 var dog = function dog(state) { return { create: function create() { console.log('Create the dog'); this.dogIsCreated(); }, dogIsCreated: function dogIsCreated() { console.log('Ready'); } } } var ted = dog().create(); 

暂无
暂无

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

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