javascript object.create metodu basit örnek
bir tane obje tanımlayıp 2 tane fonksiyon yazalım. test1,test2
const obj = { test1:function () { console.log("test1"); }, test2:function () { console.log("test2") } } console.log(obj);
gördüğümüz gibi 2 tane metodu 1 tanede proto özelliği var.
Yeni bir obje olusturup proto özelliğinde yukarıdaki yeri gösterelim. Object.create kullanıcaz. Bir obje olusturup . Bunun içine buradaki objeyi göndereceğiz
const emp = Object.create(obj); console.log(emp);
bu sekilde protoya baglamıs olduk. Bakarsak
daha sonradan buna özellik verebiliriz. verelim
bu sekilde prototip baglanabilir.
Başka örnek
-------------------------
bir tane boş constructor olusturalım.
function Person() { }
Person’ constructorumuzun prototype özelliğine 2 tane metod ekleyelim
function Person() { } Person.prototype.test1 = function () { console.log("test1"); } Person.prototype.test2 = function () { console.log("test2"); } const person = new Person(); console.log(person);
çıktımızda bakarsak her hangi bir özellik yok sadece bir tane prototype var. onun içinde test1, test2 iki tane fonksiyon var .1 tane constructorumuz var içnde de bir tane prototypemız var oda objeyi gösteriyor en dış katman.
Şimdi bunu baska bir prototype ile bağlayalım.
Emploeei Persondaki test1 ve test2 yi miras alsın. Bunu yapmamız içim Employeedeki prototype olusturmamız gerekiyor. yani Employeenin protoypinin proto özelliği Object.create diyerek Person.prototypedan olusturacagız.
function Person() { } Person.prototype.test1 = function () { console.log("test1"); } Person.prototype.test2 = function () { console.log("test2"); } function Employee(name,age) { this.name = name; this.age = age; } Employee.prototype = Object.create(Person.prototype); const emp = new Employee("ali",25); emp.test1(); // burada Persondan özellik aldık console.log(emp);
bir kendi proto muza funksiyon ekleyelim.
Employee.prototype.mytest = function () { console.log(mytest) }










