简体   繁体   English

这是什么样的设置,以及如何使用?

[英]What sort of setup is this and how to use it?

For a project I am working on I am running into some Javascript coding from a previous programmer, this is basically structured as follows. 对于我正在从事的项目,我正在使用以前的程序员编写的一些Javascript编码,其基本结构如下。

var c_test = {
    testVar : '',

    init : function()
    {
        c_test.testVar = 'Hello world!';
    },

    showMe : function()
    {
    alert(this.testVar);
    }
};

Example above created to show a basic version of the extensive coding I found like this. 上面创建的示例显示了我发现的广泛编码的基本版本。 I suppose it is some form of object orientated JS, but I am unsure how to use it properly. 我想它是某种形式的面向对象的JS,但是我不确定如何正确使用它。 For example, how would I go about calling this bit of code and running the 'showMe()' function? 例如,我将如何调用这段代码并运行'showMe()'函数?

This is called an object literal . 这称为对象文字 This is a straight forward way of building an object just by listing its properties and methods. 仅列出对象的属性和方法,这是构建对象的直接方法。

Consider c_test to be an object with two functions init and showMe and one field variable testVar c_test视为具有两个函数initshowMe和一个字段变量testVar

This is how would you call it. 这就是你的称呼。

c_test.showMe();

This can be also written as follows in OOP constructs. 也可以在OOP构造中编写如下。 But of course, technically, there are difference between these two as well. 但是,当然,从技术上讲,这两者之间也存在差异。

function c_test (){
    this.testVar = '';

    this.init= function(){
       this.testVar='Hello World';
    };

     this.showMe = function(){
       alert(this.testVar);
    };
};

Recommended Reading: 推荐读物:

http://code.tutsplus.com/tutorials/the-basics-of-object-oriented-javascript--net-7670 http://code.tutsplus.com/tutorials/the-basics-of-object-oriented-javascript--net-7670

To elaborate a little bit on Madhur Ahuja's answer, this way of coding is basically creating directly your object, as opposed to creating a "class" first and instantiating your object out of it. 为了详细说明Madhur Ahuja的答案,这种编码方式基本上是直接创建您的对象,而不是首先创建“类”并从中实例化您的对象。

This is possible because javascript is not class oriented so you can create objects directly. 这是可能的,因为javascript不是面向类的,因此您可以直接创建对象。 The drawback of this method is that it makes reuse of these kind of objects more complicated compared to creating a prototype first. 这种方法的缺点是,与首先创建原型相比,它使此类对象的重用更加复杂。

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

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