Javascript Object.create vs.prototype
(如果重复请关闭) 鉴于以下情况:Javascript Object.create vs.prototype,javascript,prototype,prototypal-inheritance,oojs,Javascript,Prototype,Prototypal Inheritance,Oojs,(如果重复请关闭) 鉴于以下情况: 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
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
。这不是一个好主意,因为虽然教师是人,但人不一定是教师:
职能人员(第一、最后){
this.name={
第一,
最后的
};
};
Person.prototype.greeting=函数(){
log('Hi!我是'+this.name.first+');
};
函数教师(第一、最后、科目){
打电话(这个,第一个,最后一个);
this.subject=主语;
}
//坏的:
Teacher.prototype=Person.prototype;
//因为:
Teacher.prototype.teachesClass=()=>true;
//Person.prototype现在也有:
const p=新人();
console.log(p.teacheslass())你真的是指Teacher.prototype.\uuu proto\uuuu=Person.prototype代码>?真奇怪。你的意思是Teacher.prototype=Person.prototype代码>?对不起,你是对的。这就是我的意思@CertainPerformanceahahahahahaha!!问题。“如果使用普通赋值方法,对Teacher.prototype的更改也会影响Person.prototype。”这是因为它指向内存中的同一个对象?确切地说,就是这样。