Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何正确地委托类原型_Javascript_Class_Oop - Fatal编程技术网

Javascript 如何正确地委托类原型

Javascript 如何正确地委托类原型,javascript,class,oop,Javascript,Class,Oop,如果你跳到第一个答案,你会看到他使用了Employee.prototype=newperson()继承Person.prototype到Employee.prototype,但是当我从Udacity学习JavaScript OOP课程时,他们使用Employee.prototype=Object.create(Person.prototype) 相反 正确的答案是什么: Employee.prototype = new Person(); 或 或 如果这个问题重复,请给我一些好的答案。Empl

如果你跳到第一个答案,你会看到他使用了
Employee.prototype=newperson()
继承
Person.prototype
Employee.prototype
,但是当我从Udacity学习JavaScript OOP课程时,他们使用
Employee.prototype=Object.create(Person.prototype)
相反
正确的答案是什么:

Employee.prototype = new Person();


如果这个问题重复,请给我一些好的答案。

Employee.prototype=Object.create(Person.prototype)是最干净的

使用
Employee.prototype=new Person()
您会发现在
Person
中分配给
的任务会影响所有
员工
实例。也许你不想那样。还有其他副作用

例如(使用一些ES2015语法):

您需要阅读
Person
代码,以了解为什么默认情况下所有员工都被称为
fred
。在这种情况下,这是微不足道的,但在现实世界中,许多函数都是长的、有状态的,并且容易误读

想象一下,如果
Person
依赖于某个外部状态。
Employee.prototype
的值可能会根据是否已执行其他代码而更改。你不希望原型链中存在这种不确定性

例如:

let personCount = 0;
function Person() {
  this.id = personCount ++;
}

// ...

Employee.prototype = new Person();
// what `id` do Employees inherit? we don't know!
// it depend on how many times `Person` has been called,
//  and by creating `Employee.prototype` we changed the state even further. Uhoh.
Object.create(Person.prototype)
更容易推理,因为没有用户函数调用;没有逻辑。您只需检查static
Person.prototype
即可查看您继承的内容

原型仍然可能具有可变值,因此存在一些不确定性,但创建对象本身的行为没有副作用,因此此类错误的可能性较小

Employee.prototype=Person.prototype,更改为
Employee.prototype
将影响所有
Person
实例。你可能不想那样

Employee.prototype = Person.prototype;
function Person(name = "fred") {
  this.name = name;
}

function Employee(...args) {
  Person.call(this, ...args);
}

Employee.prototype = new Person();


var e1 = new Employee();
console.log(e1.name); // fred
let personCount = 0;
function Person() {
  this.id = personCount ++;
}

// ...

Employee.prototype = new Person();
// what `id` do Employees inherit? we don't know!
// it depend on how many times `Person` has been called,
//  and by creating `Employee.prototype` we changed the state even further. Uhoh.