Simple .prototype Use Case

2 Questions:

  • Below Code A and Code B have the same result?

ADD after reading the answer @ Box9: How about code A or code C?

  • What is a simple, practical, intuitive coding scenario, where is code A the preferred method?

Code A: with .prototype

function employee(name,jobtitle,born)
{
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;
}

employee.prototype.salary=null;

Code B: without .prototype

function employee(name,jobtitle,born)
{
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;

    employee.salary=null;
}

C code: with .prototype, nothing inside

    function employee(){}

employee.prototype.name=null;    
employee.prototype.jobtitle=null;
employee.prototype.born=null;
employee.prototype.salary=null;

I apologize ahead of time, I understand that there were other SO questions about .prototype and many web tutorials, however these explanations seem too simplistic or just technically over my head.

+3
source share
2 answers

In your example, code A is correct, but code B is not.

To explain, we can think employeeof three different aspects:

  • "" - , . , . . .
    • prototype.
  • "" - , . ( "" ), . , , .
    • this employee().
  • - , , , . A.
    • employee.

, ,

employee.prototype.salary = null A , "" .

employee.salary = null B , , , . , employee() - , , , this "" , new employee().

+3

-, A B . A . , employee salary, null. , - , .

, A:

var e = new employee('Bob', 'janitor', 1978);
alert(e.salary);  // null

var f = new employee('Alice', 'teacher', 1976);
f.salary = 20000;

alert(f.salary);  // 20000
alert(e.salary);  // null

B , , . employee.salary . , , , . employee.RETIREMENT_AGE = 65, , ( ).

+1

Source: https://habr.com/ru/post/1786944/


All Articles