簡體   English   中英

Javascript - 如何向對象構造函數添加屬性

[英]Javascript - how do you add properties to an object constructor function

如何在 JavaScript 中為構造函數添加屬性? 例如。 如果我有以下功能。

function Hotel(name)
{
   this.name = name;
};

var hotel1 = new Hotel('Park');

我可以添加一個可以在類中本地使用的“本地”變量,就好像它是私有的,使用關鍵字“this”使用相同的符號。 當然它不會是私有的,因為創建的對象將能夠正確使用它?

我可以做這樣的事情嗎。 我是使用this關鍵字還是使用var關鍵字,它是哪一個? 我在底部的函數構造函數中有示例 2

1. var numRooms = 40;
2. this.numRooms = 40;
3. numRooms : 40,

function Hotel(name)
{
   this.name = name;
   this.numRooms = 40;
};

我知道如果我想要對象構造函數中的函數,我需要使用this詞。 正如我上面所問的那樣,這對普通變量是否也有效。

function Hotel(name)
{
   this.name = name;
   this.numRooms = 40;

   this.addNumRoomsPlusFive = function()
   {
       return this.numRooms + 5;
   }

};

您可以簡單地向構造函數添加一個私有變量:

function Hotel(name) {

    var private = 'private';

    this.name = name;
};

但是,如果你會用你的Hotel功能沒有new運營商,這是附在所有特性和功能, this將成為全球性的。

function Hotel(name) {

    var private = 'private';

    this.name = name;
};

var hotel = Hotel('test');

console.log(name); // test

在構造函數中返回一個對象是個好主意:

function Hotel(name) {

    var 
        private_var = 'private',
        private_func = function() {

            // your code
        };

    retur {

        name: 'name',
        public_func: private_func
    }
};

var hotel = Hotel('test');

console.log(name); // undefined

因此,如果您將使用沒有new運算符的Hotel構造函數,則不會創建全局變量。 只有當返回值是一個對象時,這才是可能的。 否則,如果您嘗試返回任何不是對象的東西,構造函數將繼續其通常的行為並返回this

通常它是使用閉包來執行的:

var Hotel = (function() {
      var numrooms=40; // some kind of private static variable

      return function(name) { // constructor
         this.numrooms = numrooms;
         this.name = name;
      };
}());

var instance = new Hotel("myname");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM