Javascript 相当于 PHP 的 ::(范围解析运算符)

Rol*_*olf 5 javascript php oop class scope-resolution

在 PHP 中,你可以这样做:

class myClass() {
    function doSomething(someVar) {
         // do something here
    }
    // etc... (other methods and properties)
}
Run Code Online (Sandbox Code Playgroud)

然后,当然,您可以在实例化类后调用该方法,如下所示:

$myObj = new myClass();
$myObj->doSomething();
Run Code Online (Sandbox Code Playgroud)

但是您也可以选择将该方法作为独立函数调用,而无需实例化该类(但您必须注意该函数中的依赖项),如下所示:

myClass::doSomething();
Run Code Online (Sandbox Code Playgroud)

我相信它是为 C++ 借来的东西......它被称为范围解析运算符(PHP 代码中的 Paamayim Nekudotayim......)
http://en.wikipedia.org/wiki/Scope_resolution_operator#PHP
http://www.php .net/manual/en/language.oop5.paamayim-nekudotayim.php

你会如何在 JavaScript 中做这样的事情?这似乎是不可能的。也许我以错误的方式接近这个,我应该透露我想要实现的目标......

我只有一个函数,它是这样的:

function submitContactForm(form) {
    // pretty JavaScript...
}
Run Code Online (Sandbox Code Playgroud)

我很高兴它是一个函数。但我想实现一个“resetContactForm()”,但希望以某种方式将它附加到 submitConatctForm 函数。

我知道我可能会这样做:

var contactForm = {
   "submit" : function(form) {
       //...
   },
   "reset" : function(form) {
       //...
   }
}
Run Code Online (Sandbox Code Playgroud)

我会像那样回答我自己的问题......

但是,除了我不喜欢这种语法,并想避免它之外,还有一个事实是,上面的结构不能用作类定义,它与 PHP 中的不一样......所以回到最初的问题:有没有办法让 JavaScript 结构可以同时用作类定义和独立函数的集合?

Sea*_*ira 3

您误解了原型继承 - 实际上可以使用第二个示例作为“类”定义,并且可以从“类”或“实例”调用这些方法:

// This is a normal JavaScript object
// not JSON as another commenter pointed out.
var ContactForm = {
   submit: function(form) {
       form = form || this.form;
       // general contact form submission implementation
   },
   reset: function(form) {
       form = form || this.form;
       // general contact form reset implementation
   },
   setForm: function(form) {
       this.form = form;
   }
};

// Now we will create an instance of the contactForm "class"
// We are setting the prototype of `firstContactForm`
// to point at the `contactForm` object.
// If we wanted to we could create a function on the
// ContactForm object (e. g. `create`) that would invoke
// Object.create for us. (i. e. `ContactForm.create()`)
var firstContactForm = Object.create(ContactForm);
firstForm.setForm(document.getElementById("someForm"));
firstForm.reset();

 // But, we can also use the function as a "static":
 ContactForm.reset(document.getElementById("someForm"));
Run Code Online (Sandbox Code Playgroud)

在回答问题的其他部分时,如果您想让它成为可“独立”调用的东西,您还可以允许直接传入数据,就像我们在示例中通过签入 和 所做form = form || this.form;submit那样reset

或者,您可以使用calland apply正如 @elclanrs 在他的回答中指出的那样)并始终使用this.form

 ContactForm.reset.call({form: document.getElementById("someForm")});
Run Code Online (Sandbox Code Playgroud)