Difference between prototype function and json naming function?

I created two classes of employees below, one of which uses a constructor function, and the other with a JSON record. In the constructor function print, the function is created by the prototype, therefore only one copy is saved, and objects ( emp1and emp2) use this function print.

Question: In JSON ( EmployeeNew) notation, a function printis stored in memory only as one copy? Or will each object store its own copy? What is the fundamental difference between these two approaches? What is the best for this scenario?

var Employee = function (name) {
    this.name = name;
};

Employee.prototype.print = function () {
    console.log(this.name);
}


var emp1 = new Employee("jack"),
    emp2 = new Employee("mark");

emp1.print();
emp2.print();

var EmployeeNew = {
    init: function (name) { this.name = name; },
    print: function () {
        console.log(this.name);
    }
};

var empNew1 = Object.create(EmployeeNew),
    empNew2 = Object.create(EmployeeNew)

empNew1.init("jack")
empNew1.print();
empNew2.init("jack");
empNew2.print();
+3
source share
2 answers

( , ).

...

Object.create(EmployeeNew)

... EmployeeNew. , print init .

console.log(empNew1.init === empNew2.init); // true
console.log(empNew1.print === empNew2.print); // true

, , ...

  • EmployeeNew, Object.create
  • 2 Object.create
  • , , EmployeeNew
  • EmployeeNew
  • , 2

1: EmployeeNew

var EmployeeNew = {
    init: function (name) { this.name = name; },
    print: function () {
        console.log(this.name);
    }
};

2: 2 , Object.create

var empNew1 = Object.create(EmployeeNew),
    empNew2 = Object.create(EmployeeNew)

3: , , EmployeeNew

empNew1.init("jack");
empNew1.print();
empNew2.init("jack");
empNew2.print();

4: EmployeeNew

EmployeeNew.foo = function() {
    console.log( 'Foo was invoked' );
};

5: , 2

empNew1.foo();  // logs 'Foo was invoked'
empNew2.foo();  // logs 'Foo was invoked'

, , empNew1 empNew2 EmployeeNew. , , EmployeeNew Object.create, EmployeeNew, prototype .

, , , empNew1, empNew1 , , , . , .


...

"... , this.name (name:" "), name ..."

, ...

EmployeeNew.name = "unknown"

... , EmployeeNew .

.name (), , : .name .

...

EmployeeNew.name = "unknown";

...

empNew1.name;  // "unknown"
empNew2.name;  // "unknown"

... ...

empNew1.name = "bubba";

empNew1.name;  // "bubba"
empNew2.name;  // "unknown"

, empNew1 .name, "bubba". .name empNew1, .

empNew2 .name, - .

+3

, , , init.

, ( , ), , ( , ​​ ). , .

0

All Articles