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 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...
}

そして、私はそれが機能であることを嬉しく思います。しかし、「resetContactForm()」を実装したいのですが、何らかの方法で submitConatctForm 関数にアタッチしたいと考えています。

私はおそらくこれを行うことができることを知っています:

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

そして、私は自分の質問にそのように答えたでしょう...

しかし、私はこの構文が好きではなく、避けたいという事実に加えて、上記の構造をクラス定義として使用できないという事実もあります.PHPと同じではありません...だから元の質問に戻ります: クラス定義とスタンドアロン関数のコレクションとして同時に使用できる JavaScript 構造を持つ方法はありますか?

4

4 に答える 4

3

JavaScript のオブジェクト構文では、特殊文字がない場合は引用符は必要ありません:

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

Paamayim Nekudotayim は、クラスも静的メソッドもないため、JavaScript には存在しません。しかし、JavaScript には、私たちが と呼ぶ動的なコンテキストがありますthisthisキーワードの名前を除いて、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 に答える
3

プロトタイプの継承を誤解しています-実際には2番目の例を「クラス」定義として使用でき、メソッドは「クラス」または「インスタンス」から呼び出すことができます。

// 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.

callまたは、 andを使用してapply( @elclanrs が彼の回答で指摘しているように)、常に次を使用することもできますthis.form

 ContactForm.reset.call({form: document.getElementById("someForm")});
于 2014-01-06T18:38:21.927 に答える
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();

したがって、この「機能」は JavaScript で既に利用可能であると思われますが、別の単純ではない形式ではあります。

また、Sean Vieira のアプローチは次のように完了しました。

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 に答える