简体   繁体   English

JS OO基础知识,为什么这不起作用?

[英]JS OO basics and why doesn't this work?

Aparently I fail to understand how to use simple OO patterns in JS. 显然我无法理解如何在JS中使用简单的OO模式。 Hopefully someone can just give me a hint where I am going wrong. 希望有人可以给我一个提示,我要去哪里错了。

Here is a short test. 这是一个简短的测试。 When loaded into a browser the development console shows two things: 当加载到浏览器中时,开发控制台将显示两件事:

  1. undefined as value of Element.Display and undefinedElement.Display

  2. an obviously failed assignment to Board.Display because of this 由于这个原因,对Board.Display分配显然失败了

Interesting detail: the debug output of Element does contain Display ... 有趣的细节: Element的调试输出确实包含Display ...

My question: why doesn't this work? 我的问题:这为什么不起作用?


File "test.html": 文件“ test.html”:

<html lang="en">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="test.js"></script>
    </head>

    <body>
        Hello world!
    </body>
</html>

File "test.js": 文件“ test.js”:

Element: {
    Display = function() {
        // declare something
        // do something
    } // Element.Display
}; // Element

var Board = function() {
    // debug output
    console.log(Element);
    console.log(Element.Display);
    // declare something
    Display: new Element.Display();
    // do domething
}();

The above example at jsfiddle.net: Example jsfiddle.net上的示例: 示例

Element: is a label . Element:标签

You want to assign an object to a variable: 您想要将对象分配给变量:

Element =

You should declare the variable first though. 您应该先声明该变量。

var Element =


Then we have this. 然后我们有这个。

Display = function() {
    // declare something
    // do something
} // Element.Display

Before you fix the last problem, it is valid (because it is a function assignment to a global inside a block). 在解决最后一个问题之前,它是有效的(因为这是对块内全局变量的功能分配)。

After you fix that problem it becomes an error. 解决该问题后,它将变成错误。

Use : between property names and property values inside an object literal. 在对象文字内部的属性名称和属性值之间使用:


The second half of your code has problems too. 您的代码的后半部分也有问题。

var Board = function() {
    // Also a label
    Display: new Element.Display();

    // there is no return statement in this function
    // so you are assigning undefined to Board
}();

This could help clarify things a little: 这可以帮助澄清一些事情:

Element is declared as an object with a function named 'Display'. 使用名为“ Display”的函数将Element声明为对象

var Element = {
    Display : function() {
        console.log('display something');
    } 
}; 

Board is declared as a function that calls the Display function of the Element object. 董事会声明为调用元素对象的显示功能的功能

var Board = function() {        
    return Element.Display();       
}();

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

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