Bu örnekte, JavaScript nesnelerini farklı şekillerde oluşturmayı öğreneceksiniz.
Bu örneği anlamak için, aşağıdaki JavaScript programlama konuları hakkında bilgi sahibi olmalısınız:
- JavaScript Nesneleri
- JavaScript Oluşturucu İşlevi
Bir nesneyi üç farklı şekilde oluşturabilirsiniz:
- Nesne değişmezi kullanma
- Doğrudan Object örneğini oluşturarak
- Yapıcı işlevini kullanarak
Örnek 1: Nesne değişmezi kullanma
// program to create JavaScript object using object literal const person = ( name: 'John', age: 20, hobbies: ('reading', 'games', 'coding'), greet: function() ( console.log('Hello everyone.'); ), score: ( maths: 90, science: 80 ) ); console.log(typeof person); // object // accessing the object value console.log(person.name); console.log(person.hobbies(0)); person.greet(); console.log(person.score.maths);
Çıktı
nesne John okuma Herkese merhaba. 90
Bu programda kişi adında bir nesne oluşturduk .
Bir nesne değişmezi kullanarak bir nesne oluşturabilirsiniz. Bir nesne değişmezi, ( )
doğrudan bir nesne oluşturmak için kullanılır.
Anahtar: değer çifti ile bir nesne oluşturulur .
Ayrıca bir nesnenin içindeki işlevleri, dizileri ve hatta nesneleri tanımlayabilirsiniz. Noktalı .
gösterimi kullanarak nesnenin değerine erişebilirsiniz .
Bir nesnenin örneğini kullanarak bir nesne oluşturmanın sözdizimi şöyledir:
const objectName = new Object();
Örnek 2: Doğrudan Nesne Örneğini Kullanarak Bir Nesne Oluşturma
// program to create JavaScript object using instance of an object const person = new Object ( ( name: 'John', age: 20, hobbies: ('reading', 'games', 'coding'), greet: function() ( console.log('Hello everyone.'); ), score: ( maths: 90, science: 80 ) )); console.log(typeof person); // object // accessing the object value console.log(person.name); console.log(person.hobbies(0)); person.greet(); console.log(person.score.maths);
Çıktı
nesne John okuma Herkese merhaba. 90
Burada new
anahtar kelime, Object()
bir nesne oluşturmak için örnekle birlikte kullanılır .
Örnek 3: Yapıcı İşlevini kullanarak bir nesne oluşturma
// program to create JavaScript object using instance of an object function Person() ( this.name = 'John', this.age = 20, this.hobbies = ('reading', 'games', 'coding'), this.greet = function() ( console.log('Hello everyone.'); ), this.score = ( maths: 90, science: 80 ) ) const person = new Person(); console.log(typeof person); // object // accessing the object value console.log(person.name); console.log(person.hobbies(0)); person.greet(); console.log(person.score.maths);
Çıktı
nesne John okuma Herkese merhaba. 90
Yukarıdaki örnekte, Person()
yapıcı işlevi new
anahtar sözcüğü kullanarak bir nesne oluşturmak için kullanılır .
new Person()
yeni bir nesne yaratır.