我无法理解某些事情。我一直在寻找差异一段时间,但我似乎找不到我正在寻找的答案。
我正在尝试学习 OOP javascript,我读到的每个教程似乎都有不同的继承方式,并且通常以非常复杂的方式进行解释。我现在遇到的问题与为对象创建方法有关,我正在使用 Mozilla 开发人员文档中的代码。
您将在下面的大代码块中看到,我尝试在 Person
中添加一个 jump
方法,如下所示:
Person.prototype = {
jump: function() {
console.log("Jumping")
}
}
这不起作用,它基本上破坏了整个类,告诉我 student1.walk
不是一个函数。但是,如果我将方法的声明更改为
Person.prototype.jump = function() {
console.log("Jumping");
}
当我调用这些方法时,一切都正常。从个人风格的 Angular 来看,虽然我喜欢第一种创建方法的方式,因为我不必不断重复 Person.prototype
部分,我可以继续添加一个逗号,后跟我的方法声明。我想知道这两种创建方法的方式有什么区别,因为我在任何地方都找不到答案。我想了解为什么使用第一种方法也会失败。
var Person = function(firstName) {
this.firstName = firstName;
};
Person.prototype.walk = function(){
console.log("I am walking!");
};
Person.prototype = {
jump: function() {
console.log("Jumping");
}
}
Person.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName);
};
function Student(firstName, subject) {
Person.call(this, firstName);
this.subject = subject;
}
Student.prototype = Object.create(Person.prototype); // See note below
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName + ". I'm studying "
+ this.subject + ".");
};
Student.prototype.sayGoodBye = function(){
console.log("Goodbye!");
};
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();
student1.walk();
student1.sayGoodBye();
student1.jump();
最佳答案
问题在于您通过调用 Person.prototype = {}
覆盖了整个原型(prototype)链。这使得其他方法消失,因为它们是通过重置链而从链中取出的。
它就像任何其他变量
let x = 5; //5
x = 6; // 6
这是一个简单的赋值语句,用于重新分配原型(prototype)链。
关于javascript - 创建 OOP Javascript 的误区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902739/