2

JavaScriptで同じことを行う方法はたくさんあります。しかし、私はいくつかの方法を取り上げました、そして私が率直に理解していないいくつかの方法。誰かが私がいくつかのことを明確にするのを手伝ってくれませんか?(私は最初にPHPでOOPを学びました。)

したがって、クラスは次のように作成できます。

var object = new class(constructparams) {
    var private_members; // Can be accessed from within the code inside this definition only.
    this.public_members; // Can be accessed from everywhere.

    var private_functions = function() {}
    this.public_functions = function() {}
}

object.prototype.semi_public_members = function() {
    // Will be public, but can only access public members and methods.
    // E. g. private_members; is not available here.
}

これは今のところすべて正しいですか?

次に、誰かが名前空間を作成するための自己実行無名関数アプローチが好きです。上記の方法で同じことを行うと、名前空間が提供されるというのは、そのポイントは何ですか?

そして最後に、私が理解していないオブジェクトリテラル表記があります。

var object = { // Something strange in here }

そこで何が起こっているのですか?JSONですか?どのように使用されますか、どのように使用できますか。私が説明した方法を使用する代わりに、この方法を使用することの利点は何ですか?初めてクラスを正しく作成するのではなく、なぜプロトタイプを作成するのですか?

4

4 に答える 4

5

構築されたオブジェクト内のさまざまなものの動作を例で説明します。

// Defined as a variable from an anonymous function
// so that there is scope closure over variables
// shared across all instances and the prototype.
// If this isn't important, you don't need to close
// scope around it, so define directly
var ConstructedObject = (function constructorCreator () {
    // Define any variables/methods to be shared across
    // all instances but not polluting the namespace
    var sharedVariable = 'foo';

    // Next the actual constructor
    function ConstructedObject () {
        // Variables here are normally used to help
        // each instance and will be kept in memory as
        // long as the instance exists
        var instanceVariable = 'bar';
        // instance-specific properties get defined
        // using the "this" keyword, these are the
        // properties expected to be changed across
        // each different instance
        this.instanceProperty = true;
        this.instanceMethod = function () { return instanceVariable; };
        this.changeInstanceVar = function () { instanceVariable = 'foo'; };
            // you do have access to the shared
            // variables here if you need them.
    }
    // After the constructor, you set up the
    // prototype, if any. This is an object of shared
    // properties and methods to be inherited by every
    // instance made by the constructor, and it also
    // inherits the prototype's prototype, too.
    // Lets use a literal object for simplicity.
    ConstructedObject.prototype = {
        // Accessing the instance to which a method
        // applies is done using the "this" keyword,
        // similar to in the constructor
        sharedMethod : function () { return [sharedVariable, this.instanceMethod(),this.instanceProperty]; },
        changeSharedVar : function () { sharedVariable = 'bar'; }
        // properties may also be defined
    };
    // Finally, the constructor is returned so it
    // can be kept alive outside of the anonymous
    // function used to create it
    return ConstructedObject;
// and the anonymous function is called to execute
// what we've done so far
})();

上記のコードを実行すると、インスタンス固有の変数と共有変数の両方を使用してオブジェクトを作成するコンストラクターができます。次に、2つのインスタンスを作成し、いくつかの変更の前後でそれらを比較することによって、それらがどのように動作するかを見てみましょう。

// First create the two instances
var myObjA = new ConstructedObject(),
    myObjB = new ConstructedObject();
// Now compare them, the sharedMethod method we
// used in the prototype offers an easy way to
// do this
console.log( myObjA.sharedMethod(), myObjB.sharedMethod() );
// ["foo", "bar", true] ["foo", "bar", true]
// Next lets change the different variables in
// myObjB so we can see what happens, again the
// change* methods defined before let us do this
// easily
myObjB.changeInstanceVar();
myObjB.changeSharedVar();
// For completeness, lets also change the property
// on myObjB.
myObjB.instanceProperty = false;
// Now when we compare them again, we see that our
// changes to the myObjB instance have only changed
// the shared variables of myObjA
console.log( myObjA.sharedMethod(), myObjB.sharedMethod() );
// ["bar", "bar", true] ["bar", "foo", false]

見やすくするために、ログに記録された2つのステートメントをまとめます。

//     myObjA               myObjB
["foo", "bar", true] ["foo", "bar", true]
["bar", "bar", true] ["bar", "foo", false]
于 2012-11-03T23:31:06.430 に答える
1

欠けていると思われるコンセプトもあると思いますが、できる限りお答えしていきたいと思います。

だから、このようにクラスを作ることができます...これは今のところすべて正しいですか?

近いですが、完全に正しいわけではありません。コンストラクター関数を作成する必要はありませんnew。「クラス」の新しいインスタンスを作成するときにのみ必要です。

function Klass() { ... } // capitalized name as convention for constructors
var myKlass = new Klass(); //<-- Need "new" here

パブリックメソッドは、インスタンスまたはプロトタイプにアタッチできます。プロトタイプにアタッチすると、メソッドはすべてのインスタンスで共有され、メモリを節約できます。

Klass.prototype = {
  publicSharedMethod: function() {
    var self = this;
  }
}

次に、誰かが自己実行型の無名関数が好きです...そのポイントは何ですか...

モジュールパターン(または自己実行関数)のアプローチは少し異なります。これは、通常、プロトタイプを処理することはできますが、処理しないためです。これは、プロパティとメソッドを持つリテラルオブジェクトを返す関数ですが、そのオブジェクトのインスタンスが必要ない場合は、主にシングルトンに使用します。

var Singleton = (function() {
  var private = 'foo';
  var public = 'baz';
  var publicMethod = function() { ... }
  // Expose public methods and properties
  return {
    public: public
    publicMethod: publicMethod
  }
}());

そして最後に、私が理解していないオブジェクトリテラル表記があります。

これは、PHPが「連想配列」と呼ぶものと同様に、JavaScriptの通常のオブジェクトです。リテラルオブジェクトの構文はJSONのベースですが、JSONにはフォーマットに関してより多くの制限があります。JavaScriptはより寛容であるため、たとえば引用符で囲まれていないプロパティやメソッドを使用できます。

初めてクラスを正しく作成するのではなく、なぜプロトタイプを作成するのですか?

ここでのポイントは、JavaScriptは従来のオブジェクト指向言語ではないため、クラスがなく、クラスについて考える必要がないことを理解することです。しかし、プロトタイプは非常に強力であり、クラスよりもさらに強力だと思います。プロトタイプを使用してクラスを複製する方法については、オンラインで多くの例がありますが、その逆はありません。

于 2012-11-03T22:21:03.997 に答える
0

いいえ、それは正しくありません。コンストラクター関数は、オブジェクトの作成とは別にする必要があります。

function myClass(constructparam1) {
  this.public_member = constructparam1; // Can be accessed from everywhere.
}

メソッドは、インスタンスではなく、コンストラクターのプロトタイプに含まれている必要があります。

myClass.prototype.semi_public_members = function() {
  // Will be public
}

newキーワードを指定してコンストラクターを呼び出し、インスタンスを作成します。

var obj = new myClass(1337);

コンストラクター関数内のローカル変数には、その関数内でのみアクセスできます。クラスにローカル変数を入れたくない場合は、プロトタイプのメソッドが変数にアクセスできるように、クロージャを作成するためにその周りに関数が必要です。

var myClass = (function(){

  var local_variable;

  function constructor(constructparam1) {
    this.public_member = constructparam1; // Can be accessed from everywhere.
  }

  constructor.prototype.semi_public_members = function() {
    // Will be public
    alert(local_variable); // can access private variables
  }

  return constructor;
})();

オブジェクトリテラルは、オブジェクトを一度に作成するための単純ですが制限された方法です。それらにはプロトタイプがないため、メソッドを持たせたい場合は、プロパティに割り当てる必要があります。

var obj = {

  public_member: 1337,

  semi_public_members: function(){
    alert(this.public_member);
  }

};
于 2012-11-03T22:12:11.020 に答える
0
var object = new function () {
    //
}

var myObject = new object();
于 2012-11-03T22:13:21.527 に答える