English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript基础教程

JavaScript 对象

JavaScript 函数

JS HTML DOM

JS 浏览器BOM

AJAX 基础教程

JavaScript 参考手册

Costruttore degli oggetti JavaScript

在前面的章节中,我们学习了如何在JavaScript中创建对象。

前几章中的示例是有限的。它们仅创建单个对象。

有时我们需要一个“ 模型”来创建许多相同类型的对象(示例)。

创建“模型”的方法是使用对象构造函数

一个对象的构造函数可以很容易地创建多个对象(示例)具有相同的属性和方法。

在下面的示例中,function User()是一个对象构造函数:

  function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
  }

通过使用new关键字调用构造函数来创建相同类型的对象:

var Seagull = new User("Seagull", "Anna", 22, "New Delhi");
var tarush = new User("Tarush", "Balodhi", 34, "Bihar");
Testa a vedere‹/›

Come potete vedere, possiamo costruire rapidamente un gran numero di oggetti utente diversi chiamando il costruttore User con parametri diversi. Questo è lo stesso schema utilizzato da JavaScript nei suoi costruttori integrati (come Array() e Date()).

thisParola chiave

JavaScript ha una parola chiave speciale this, che si può usare nei metodi per fare riferimento all'oggetto corrente.

Quando this viene utilizzato in un oggetto, il suo valore è l'oggetto stesso.

In un costruttore, this non ha un valore. Sostituisce l'oggetto nuovo. Quando si crea un nuovo oggetto, il valore di this diventa l'oggetto nuovo.

Aggiungere proprietà a un oggetto

Per aggiungere nuove proprietà a un oggetto, è possibile assegnare un nuovo valore all'attributo utilizzando l'operatore di assegnazione (=).

Seagull.weapon = "Sword";
Testa a vedere‹/›

Attenzione:Questa proprietà sarà aggiunta a Seagull. Non lo è (non si applica a nessun altro oggetto User).

Aggiungere metodi a un oggetto

Per aggiungere nuovi metodi a un oggetto, è possibile assegnare una nuova funzione all'attributo utilizzando l'operatore di assegnazione (=).

Seagull.greet = function() {
return "Hello World";
};
Testa a vedere‹/›

Attenzione:Questo metodo sarà aggiunto a Seagull (non si riferisce a nessun altro oggetto User).

Aggiungere proprietà al costruttore

Non possiamo aggiungere nuove proprietà al costruttore come facciamo con un oggetto esistente:

User.weapon = "Sword";
Testa a vedere‹/›

Per aggiungere nuove proprietà a una funzione costruttiva, è necessario aggiungerle all'interno della funzione costruttiva:

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
   this.weapon = "Sword";
}
Testa a vedere‹/›

A volte, vorremmo aggiungere nuove proprietà a una funzione costruttiva in una fase successiva, proprietà che saranno condivise tra tutti gli oggetti (esempi). La risposta èOrigine degli oggetti

Aggiungere metodi al costruttore

Il costruttore può anche definire metodi.

noiNon possiamo fare comeAggiungere metodi a una funzione costruttiva è lo stesso di aggiungere metodi a un oggetto esistente.

Aggiungere metodi a un oggetto deve essere fatto all'interno del costruttore.

function User(fname, lname, age, loc) {
   this.firstName = fname;
   this.lastName = lname;
   this.age = age;
   this.location = loc;
   this.fullName = function() {
   return this.firstName + " " + this.lastName;
   };
}
Testa a vedere‹/›

A volte vorremmo aggiungere nuovi metodi a una funzione costruttiva in una fase successiva, metodi che saranno condivisi tra tutti gli oggetti (esempi). La risposta èOrigine degli oggetti

Costruttore integrato di JavaScript

JavaScript ha i seguenti costruttori nativi per oggetti:

let x1 = new String(); // Un nuovo oggetto String.
let x2 = new Number(); // Un nuovo oggetto numero.
let x3 = new Boolean(); // Un nuovo oggetto booleano.
let x4 = new Object(); // Un nuovo oggetto Object.
let x5 = new Array(); // Un nuovo oggetto Array.
let x6 = new RegExp(); // Un nuovo oggetto RegExp.
let x7 = new Date(); // Un nuovo oggetto data.
let x8 = new Function(); // Un nuovo oggetto funzione.
Testa a vedere‹/›

Non dichiarare Number, String o Boolean come oggetti

Come puoi vedere sopra, JavaScript ha oggetti di tipo dati fondamentali: String, Number e Boolean.

Non abbiamo ragione per creare oggetti complessi. Poiché i valori primitivi sono molto più veloci.

Sempre considera numeri, stringhe o valori booleani come valori primitivi. Non come oggetti.

Declinare questi tipi come oggetti ridurrà la velocità di esecuzione e produrrà risultati imprevisti.

var str1 = "New Delhi";
var str2 = new String("New Delhi");
document.write(str1 === str2); // restituisce un errore perché str1 e str2 hanno tipi diversi
Testa a vedere‹/›

Impossibile confrontare gli oggetti:

var str1 = new String("New Delhi");
var str2 = new String("New Delhi");
document.write(str1 == str2); // restituisce un errore perché str1 e str2 hanno tipi diversi
document.write(str1 === str2); // r restituisce un errore perché str1 e str2 hanno tipi diversi
Testa a vedere‹/›

Puoi anche fare così:

  • Usa {} al posto di new Object()

  • Usa "" al posto di new String()

  • Usa 0 al posto di new Number()

  • Usa false al posto di new Boolean()

  • Usa [] al posto di new Array()

  • Usa /()/ al posto di new RegExp()

  • Usa function (){} al posto di new Function()

let x1 = {};
let x2 = "";
let x3 = 0;
let x4 = false;
let x5 = [];
let x6 = /()/;
let x7 = function(){};
Testa a vedere‹/›

Primitivi di stringa e oggetti di stringa

Di solito, le stringhe in JavaScript sono valori originali creati con literals: var city = "New Delhi";.

Ma può anche essere utilizzato il prefisso new per definire una stringa come oggetto: var city = new String("New Delhi");.

In " Stringhe JS In una sezione saprete perché non si dovrebbe creare stringhe come oggetti.

Primitivi numerici e oggetti numerici

Di solito, i numeri in JavaScript sono valori originali creati con literals: var num = 50;.

Ma può anche essere utilizzato il prefisso new per definire un numero come oggetto: var num = new Number(50);.

In " Numeri JS In una sezione saprete perché non si dovrebbe creare numeri come oggetti.

Primitivi booleani e oggetti booleani

Di solito, i valori booleani in JavaScript sono valori originali creati con literals: var x = false;.

Ma può anche essere utilizzato il prefisso new per definire un valore booleano come oggetto: var x = new Boolean(false);.

In " Valori booleani JS In una sezione saprete perché non si dovrebbe creare valori booleani come oggetti.