javascript - Object.create 与 .prototype
问题描述
(如果重复请关闭)
鉴于以下情况:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
//Teacher.prototype = Person.prototype;
//Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
const t = new Teacher('John','Smith','Math');
使用这个有什么区别?
Teacher.prototype = Person.prototype;
or this
Teacher.prototype = Object.create(Person.prototype);
解决方案
如果你使用普通的赋值方法,对 的更改Teacher.prototype
也会影响Person.prototype
. 这不是一个好主意,因为虽然 Teacher 是 Person,但 Person 不一定是 Teacher:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Bad:
Teacher.prototype = Person.prototype;
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype now has that too:
const p = new Person();
console.log(p.teachesClass());
现在,两个.prototype
s 是相同的,因此对一个的任何突变都会影响另一个。这几乎不是你想要的。
相反,当您使用该Object.create
方法时,分配 toTeacher.prototype
只会影响Teacher.prototype
. Teacher.prototype
继承自 ,的对象Person.prototype
不会改变:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Good:
Teacher.prototype = Object.create(Person.prototype);
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype does not have teachesClass
const p = new Person();
console.log(p.teachesClass);
查看原型链:
Teacher.prototype = Person.prototype;
// You get:
Teacher.prototype <- Object.prototype
Person.prototype <- Object.prototype
Teacher.prototype === Person.prototype // (same object)
// Compare to
Teacher.prototype = Object.create(Person.prototype);
// You get:
Teacher.prototype <- Person.prototype <- Object.prototype
推荐阅读
- oracle - Oracle Apex:使用替换字符串从表字段动态链接 - 如何?
- entity-framework-core - .NET Core 3.1 - 实体框架 - 嵌入式对象
- python - 如何知道 conda 降级是否会破坏 conda 和 python 环境?
- python - 如何用python打开大端编码(ieee-be)?
- reactjs - ReactJS 中是否有类似 FindOrCreate 的方法
- reactjs - 错误:未实现:HTMLFormElement.prototype.submit
- java - Maven 插件中的 JUnit 扩展导出
- javascript - 对 Socket IO 做出反应:广播不起作用
- excel - 下拉菜单转到特定行
- c# - 实现变量类类型