6

在 PHP 中,您可以执行以下操作:

class myClass() {
    function doSomething(someVar) {
         // do something here
    }
    // etc... (other methods and properties)
}

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

$myObj = new myClass();
$myObj->doSomething();

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

myClass::doSomething();

我相信这是为 C++ 借来的东西...它被称为范围解析运算符(PHP 代码中的 Paamayim Nekudotaim...)
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...
}

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

我知道我可能会这样做:

var contactForm = {
   "submit" : function(form) {
       //...
   },
   "reset" : function(form) {
       //...
   }
}

我会这样回答我自己的问题......

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

4

4 回答 4

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"));

在回答您问题的另一部分时,如果您想让它成为可调用的“独立”,您还可以允许直接传入数据,就像我们在示例中所做的那样,我们在和中form = form || this.form;进行检查。submitreset

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

 ContactForm.reset.call({form: document.getElementById("someForm")});
于 2014-01-06T18:38:21.927 回答
3

在 JavaScript 的对象语法中,如果没有任何特殊字符,则不需要引号:

var obj = {
   key: function() {
     ...
   },
   ...
}

Paamayim Nekudotayim 在 JavaScript 中没有位置,因为没有类,没有静态方法。但是 JavaScript 有一个动态上下文,我们称之为this. this除了关键字的名称外,它与 PHP 或其他经典继承​​语言没有任何相似之处。

一个典型的 JavaScript“类”如下所示:

// A "Class"
var Person = (function(){
  // Private stuff, shared across instances
  var instances = [];

  // The constructor AKA "__construct"
  function Person(name) {
    this.name = name;
    instances.push(this); // keep track of instances
  }

  // Static methods, attached to the constructor
  // don't need an instance
  Person.instances = function() {
    return instances;
  };

  // Public methods
  Person.prototype = {
    say: function() {
      return this.name +' says hello!';
    }
  };

  return Person;
}());

现在,你如何使用它:

var mike = new Person('Mike');
mike.say(); //=> Mike says hello!
Person.instances().length; //=> 1

到目前为止这么好。至于 JavaScript 中的“作用域解析”,可以显式传递上下文;知道这this是动态的,您可以借用 Person 的say方法并在任何其他上下文中调用它,例如:

Person.prototype.say.call({name:'John'}); //=> John says hello!
于 2014-01-06T18:42:26.670 回答
2

您可以将其设为这样的类:

function ContactForm(form) {
    this.form = form;
}

ContactForm.prototype.submit = function() {
    console.log('submiting: ' + this.form);// do something with the form
}

ContactForm.prototype.reset = function() {
    console.log('reseting: ' + this.form);
}



var someForm = ...;

var form = new ContactForm(someForm);

form.submit();
form.reset();

或者,如果您想静态使用它们,您可以执行以下操作:

var ContactForm = (function() {
    var reset = function(form) {
        console.log('reseting' + form);
    };

    var submit = function(form) {
        console.log('submiting' + form);
    }

    return {
        submit: submit,
        reset: reset
    }
}()); // note that this is self-executing function

并像使用它一样

ContactForm.submit(form);
ContactForm.reset(form);
于 2014-01-06T18:36:02.617 回答
1

阅读 Sean Vieira 和 elclanrs 的答案让我有了更好的洞察力。我提出了这段代码作为概念证明,并确保我理解我正在阅读的内容。这本质上是 elclanrs 答案的简化版本:

function contactForm(form) {
    this.form = form;
}
contactForm.prototype.submit = function() {
    alert("submit "+this.form);
}
contactForm.prototype.reset = function() {
    alert("reset "+this.form);    
}

// Without instanciating:
contactForm.prototype.submit.call({form:'form2'});

// With instance:
myForm = new contactForm('form1');
myForm.reset();

所以它接缝了这个“功能”已经在 J​​avaScript 中可用,尽管是以一种不同的、不太直接的形式。

此外,肖恩·维埃拉的方法完成了:

var ContactForm = {
   submit: function(form) {
       form = form || this.form;
       alert("submit "+form);
   },
   reset: function(form) {
       form = form || this.form;
       alert("reset "+form);
   },
   createForm: function(form) {
       var myForm = Object.create(this);
       myForm.setForm(form);
       return(myForm);
   },
   setForm: function(form) {
       this.form = form;
   }
};

// instanciated
myContactForm = ContactForm.createForm('Me Form');
myContactForm.submit();

// no instance
ContactForm.submit("Some Form");

另外(我的贡献),使用包装函数怎么样?对我来说似乎是一个不错的选择。

function contactForm(form) {
    this.form = form;
    this.submit = function() {
        submitContactForm(this.form)
    }
    this.reset = function() {
        resetContactForm(this.form);
    }
}
function submitContactForm(form) {
    alert("submit "+form);
}
function resetContactForm(form) {
    alert("reset "+form);    
}

// Without instanciating:
submitContactForm('form2');

// With instance:
myForm = new contactForm('form1');
myForm.reset();

没有完美的解决方案...

于 2014-01-06T19:29:46.283 回答