JavaScriptのコンストラクタを理解する簡単なガイド


目次

  • An Introduction To Constructors
  • Functions, Constructors And The new Operator
  • Constructors And Prototypal Inheritance
  • JavaScript's Built-In Constructors
  • Closing Thoughts
  • コンストラクタ入門

    In the previous article in this series, we looked at prototypal inheritance in JavaScript and talked about important object-oriented (OOP) JavaScript concepts like the prototype, the prototype chain, inheritance, and more. We also looked at how to set an object's prototype using its __proto__ property (we noted that this is not the recommended way.) and dealt with the this variable in detail.
    You can read through this article below:



    この記事では、JavaScriptでオブジェクトのプロトタイプを設定するための推奨された方法を見て、我々が出発した場所を取り上げます.
    これを行うにはいくつかの方法がありますが、ここでのフォーカスは関数コンストラクタです.

    We will deal with the other recommended methods in the upcoming articles in this series. Talking in detail about all of them; in a single article would make it very long and grueling to read!



    コンストラクタ
    JavaScriptのコンストラクタは、オブジェクトを構築するのに使用される特別な関数です.このトピックは難しいと威圧的に表示される可能性がありますが、それは実際には非常に簡単です.

    💡 The key to understanding constructors is to know that they are actually normal JavaScript functions. What makes them special is that they are always invoked along with a very powerful operator in JavaScript called the new operator.


    以下のコードを実行し、その結果を考慮してください.
    関数Person ()
    これ.FirstName = "ロレンス"
    これ.名前は"イーグルス"
    これ.職業=「ソフトウェア開発者」
    これ.性=男性

    constロレンス= new person ()
    コンソール.ロレンスログ;
    我々の小さな工夫された例は新しいオブジェクトを作成して、ロレンス変数でそれにリファレンスを格納します.このオブジェクトは、Personコンストラクターで指定されたすべてのプロパティを持ちます.
    Person関数自体は通常のJavaScript関数ですコンストラクタのパワー(オブジェクトを構築する権限)はこのコード行です:
    const Lawrence = new Person();  
    

    ✨ The new operator modifies the behaviour of the function it operates on. Using this along with some JavaScript design patterns, we are able to create powerful constructors. We will elaborate on this in the next section.


    2 .関数、コンストラクタおよび新しい演算子

    In section 1 we learned that when the Person constructor, (or any other constructor) is invoked without the new operator it is invoked as a regular JavaScript function. In this section, we will elaborate on this with code examples.
    Kindly consider the code below.

    function Person () {
         this.firstname = "Lawrence"
         this.lastname = "Eagles"
         this.occupation = "Software Developer"
         this.gender = "male"
    }
    

    Above is the declaration of the Person function. We can notice two things from it viz:

    • It sets some properties e.g firstname, lastname, occupation, and gender to the object the this variable binds (or is pointing) to. In this case the global object.

    💡 As mentioned in the previous article in this series, one rule of the this variable is that when it is used inside a function it points to the global object but when it is used inside a method (a function in an object) it would point to that object

    If this is not very clear to you, feel free to visit my previous article on OOP JavaScript. I have already provided a link to it in section 1.
    However, here is a quick recap.
    Kindly run the code below and consider its result

    const devName = "Lawrence Eagles" function tellDevName () { console.log("result", this.devName) } tellDevName(); // returns "Lawrence Eagles"

    The above example shows that the this variable inside a function is pointing to the global object.

    • Another thing that should be pretty obvious about the Person function is that it does not have a return statement hence when invoked it would return undefined.

    💡 The JavaScript engine would return undefined from any function that does not return a value. This behaviour is leveraged in creating constructors as we are able to modify what that function returns using the new operator. Hence it is a common pattern in JavaScript, that constructors do not have a return statement


    新しい演算子
    これは、関数の特定の動作を変更する機能を持つ非常に強力なJavaScript演算子です.
    新しい演算子は非常に混乱し、最初はやや威嚇することができます.

    The key to understanding it is to always see it as another regular JavaScript operator. Hence, a good understanding of operators in JavaScript is necessary to grasp the power of this operator.



    演算子
    演算子は、通常の関数と構文的に異なる特別なJavaScript関数です.通常のJavaScript関数オブジェクトではなく、コンソールに渡します.dir ()はエラーをスローします.下記のコード例を見ることができます.
    以下のコードを実行し、結果を考慮してください.
    関数telldevname ()
    コンソール.log ("result ",このデーモン)

    コンソール.dir ( function property , telldevname )
    コンソール.dir ( function property , date )
    //以下の行のコメントを外し、コードを実行するとエラーが発生します.
    //コンソールdir ( function properties ,+)
    //コンソールdir ( function property , new )

    💡 The console.dir() displays an interactive list of the properties of the specified JavaScript object



    コードを実行するときに、TellDevName関数と日付コンストラクターのすべてのプロパティを見ることができますが、パラメーターとして演算子を渡した行をコメント解除し、コードを実行しようとすると、runkitはエラーをスローします.
    演算子は通常の関数と同じようにパラメタをとります(これはオペランドと呼ばれますが、通常の関数とは異なり、以下の三つの表記のいずれかの形式になる便利な構文を与えます.
  • この表記法では、演算子はオペランドの間に配置されます.
    以下のコードをご利用ください.
  • 2 + 2 // returns 4
    3 * 3 // returns 9
    4 - 4 // returns 0
    5 / 5 // returns 1
    6 % 2 // returns 0
    
    上の例では、各演算子は2つのパラメーター(オペランド)の間に座り、値を返します.Learn more about the infix notation here
  • Postfix記法:この記法では、演算子はオペランドに従います.
    以下のコードをご利用ください.
  • const mixNumbers = [1,2,3,4,5,6,7,8,9,10,11,12]
    const evenNumbers = []
    for (let i=0; i < mixNumbers.length; i++) {
        if (mixNumbers[i] % 2 === 0){
           evenNumbers.push(mixNumbers[i])
        }
    }
    console.log("even numbers", evenNumbers)
    
    上記の数字のリストから偶数を見つける小さな例です.しかし、この例から私たちに関心があるのは増加演算子です.
    デクリメント演算子もあります.Learn more about the postfix notation
    以下のコードをご利用ください.
    i++ increment operator
    i-- decrement operator
    
  • プレフィックス表記:この表記では、演算子がオペランドを前にします.Learn more about the prefix notation
    以下のコードをご利用ください.
  • !true               // logical NOT (!) returns false
    !false              // logical NOT (!) returns true
    ++i                 // prefix increment             
    --i                 // prefix decrement
    new constructor()   // returns the newly constructed object
    
    上の例から、新しい演算子が接頭辞表記を使用して関数(コンストラクタ)呼び出しを行い、新しく構築されたオブジェクトを返すことがわかります.

    🎉 I do hope that our succinct discourse on operators, would make you understand the new operator better and hence further your understanding of function constructors


    演算子の理解によって、新しい演算子が実際に関数(コンストラクタ)呼び出しをそのパラメータ(オペランド)として受け取り、それを操作して値を返すことがわかります.
    以下は関数コンストラクタの新しい演算子の操作です.
  • 空のオブジェクトを作成し、新しく作成したオブジェクトにこの変数をバインドします.
  • 関数がそれ自身のオブジェクトを返さない場合(この関数はコンストラクタがreturn文を持っていない場合).
    以下のコードを実行し、結果を考慮してください.
  • //正規関数
    関数Person ()
    const regularDeveloper = person ()
    コンソール.log ("通常の関数の結果", regularDeveloper )
    //コンストラクタ
    関数Person ()
    コンソール.ログ("これは"これにバインドされます", "

    コンストラクタ
    コンソール.log ("person constructor result ",コンストラクタ開発者)
    関数BadPerson ()
    コンソール.ログ("これは"これにバインドされます", "
    返り値{ name :"ジャック"

    新しい定数
    コンソール.log ("BadPersonのコンストラクタ結果", BadJack )
    上のコード例から、意図的に3つの関数のうち2つを同じ名前で与えていますが、JavaScriptが大文字小文字を区別しているので2つの異なる関数です.コンストラクタの名前の最初の文字が大文字であることに注意してください.

    💡 We use this pattern in JavaScript to differentiate constructors from regular functions. The first letter of a constructor's name is always capitalized. This would also serve as a reminder for you to use the new operator with every constructor. In our code example above, Person is the constructor and person is the regular function.


    上記のコードの結果から、通常の関数が期待通りに未定義であることを返しますが、コンストラクターはこの演算子にこの変数をこのオブジェクトにバインドする新しい演算子によって作成された新しいオブジェクトを返します.

    💥 Also notice the BadPerson constructor that returns its own object fails to return the object created from the new operator. This is a pitiful we must avoid. Again, as a rule, a constructor should not have a return statement❗




    コンストラクタを作成するためのJavaScriptデザインパターン
    コンストラクタと新しい演算子の知識によって、新しく構築されたオブジェクトに簡単にプロパティを追加できます.これは一般的なJavaScriptパターンです.
    以下のコードを親切に考えてください
    function Person () {
         this.firstname = "Lawrence"
         this.lastname = "Eagles"
         this.occupation = "Software Developer"
         this.gender = "male"
    }
    
    ここでの唯一の制限は、このコンストラクターによって作成されたオブジェクトは常にこれらのプロパティを持つことです.オブジェクトのプロパティを動的にするために、コンストラクタに対してパラメータとして渡すことができます(コンストラクターは最初の場所で正規の関数ですから).
    以下のコードを実行してください.
    関数Person (姓、姓、職業、性別)
    これ.firstname = firstname
    これ.名前の変更
    これ.職業=職業
    これ.性=ジェンダー

    新しい人(「ロレンス」、「イーグルス」、「ソフトウェア開発者」、「男性」)
    新しい人(「ベン」、「カーソン」、「神経外科医」、「男性」)
    コンスト科学者=新しい人
    コンソール.log ("開発者",開発者))
    コンソール.ログ(「ドクター」)
    コンソール.ログ(「科学者」、科学者)
    上記のコードを実行した結果から、各コンストラクターに渡された引数が参照できることがわかります.新しい演算子を使用して呼び出されると、新しく構築されたオブジェクトのプロパティが設定されます.
    You can read more about the new operator at MDN .
  • 最後に、新しい演算子リンクは、新しくつくられたオブジェクトのプロトタイプを他のオブジェクトにリンクします.
    我々の紹介では、我々はオブジェクトのプロトタイプを設定するための推奨される方法について話をするつもりであり、フォーカスは関数コンストラクタについて述べた.この点は、我々の長い談話を主題に戻します.次のセクションでそれについてもっと話しましょう.
  • コンストラクタとプロトタイプ継承

    In JavaScript, every function has a property called the prototype. This sits as an empty object in the function and remains dormant throughout the life of that function. It would only become active and quite useful if that function is used as a constructor.

    💡 The prototype property of a function (which is an object in JavaScript) is not the prototype of that function object but it acts as the prototype of any object constructed with that function when it is used as a constructor. The naming is a little confusing but we love our JavaScript 😉

    Kindly run the code below and consider its result:

    function Person (firstname, lastname, occupation, gender) { this.firstname = firstname this.lastname = lastname this.occupation = occupation this.gender = gender } // lets add some properties to the prototype property of the Person constructor. Person.prototype.getPersonBio = function () { console.log("Hello my name is " + this.lastname + " " + this.firstname + " I am a " + this.occupation ) } const Developer = new Person("Lawrence", "Eagles", "Software Developer", "Male") const Doctor = new Person("Ben", "Carson", "Neurosurgeon", "Male") const Scientist = new Person("Albert", "Einstein", "Scientist", "Male") console.log("Developer's bio:", Developer.getPersonBio()) console.log("Doctor's bio:", Doctor.getPersonBio()) console.log("Scientist's bio", Scientist.getPersonBio())

    From the results of the code above we can see that all the objects constructed with the Person constructor have access to the getPersonbio method which sits in the prototype property of the Person constructor. As we have noted above this property becomes the prototype of each object.

    The details of how the search is made down the prototype chain in other for all the constructed object to access the getPersonBio method has already been discussed in the previous article. I would kindly suggest you take a look at it if this section is not very clear to you.

    JavaScriptの組み込みコンストラクタ

    JavaScript comes with some built-in constructors. If you are a JavaScript developer, there is a high probability that you have used some of them.
    Kindly run the code below and consider its result:

    const NumObject = new Number("20") const StringObject = new String("Hello World") const Today = new Date() console.log(NumObject) console.log(StringObject) console.log(Today)
    From running the codes above we can see that each returns an object because every constructor in JavaScript returns an object.
    You can learn more about each of these built-in constructors from the links below:
    Number Constructor
    String Constructor
    Date Constructor

    These are just a selected few you can get a more robots list here


    思考の閉鎖

    I do hope you followed through to this point. If you did you are really appreciated. It has been a long discussion, and I hope you got a thing or two. If so, I would now be looking forward to hearing your opinions, comments, questions, or requests (in case anything is not clear) in the comments section below.