2017-02-10 40 views
0

在斯威夫特内JavaScript类我可以实例中的另一个类的属性和使用像调用它的方法:使用其他不同类

newClass.anotherClass.methodInTheOtherClass(); 

我不能做到这一点在JavaScript中。下面的代码产生一个错误在这一行:

var cowCommunication = new CowCommunication(); 

什么是实现这一目标,并进行以下脚本工作的正确方法?

<html > 
    <script type = "text/javascript" > 
    let CowCommunication = { 
    sayMoo: function() { 
     alert("hey"); 
    } 
    }; 
let farmTools = { 
    var cowCommunication = new CowCommunication(); 
}; 
farmTools.cowCommunication.sayMoo(); 

</script> 
</html > 

这是我真正努力使工作的代码一个真实的例子。

+1

您不能在javascript中使用对象初始值设定项中的'var'关键字,这是您的主要问题。查找正确的方式来在javascript中实例化对象。 –

回答

4
let farmTools = { 
    cowCommunication : new CowCommunication(), 
}; 

let farmTools = { 
    var cowCommunication = new CowCommunication(); 
}; 

另外:

class CowCommunication { 

    sayMoo() { 
     alert("hey"); 
    } 
} 

不:

let CowCommunication = { 
    sayMoo: function() { 
     alert("hey"); 
    } 
    } 
+0

谢谢@Abdenour!我试过,并收到test.html:10 Uncaught TypeError:CowCommunication不是一个构造函数 –

+0

好的..我相应地更新了答案。 .☝ –

+0

现在可以吗? @MarkPurpelio –

0

您还可以使用成分而不是类。

let cowCommunication = { 
    sayMoo: function() { 
     console.log('hey') 
    } 
}; 

const farmTools = function() { 
    return Object.assign({}, cowCommunication) 
} 

let instance = farmTools() 

instance.sayMoo() 
+0

谢谢!但你最终与“instance.sayMoo()”我需要“farmTools.cowCommunication.sayMoo();”我需要点,第二课以及第二课的方法,可以这么说 –

+0

该方法实际上来自第二个对象,它只是没有用这种方式表示;它只是通过原型的方式从第一个对象继承而来,这就是JS的类系统。 – thesublimeobject