我是 JS 新手。
我正在 JSFiddle 中进行实验。
我创建了一个对象 A,然后创建了两个新对象 B 和 C,如下所示。
debugger;
var A = {
name:"h",
lastname:'n',
address:'B'
};
A.getname = function()
{
console.log(this.name);
};
var B = Object.create(A);
var C=new Object();
C.prototype = A;
console.log(B.lastname);
console.log(C.lastname);
A.getname();
B.getname();
C.getname();
我采用了 javascript:Good Parts book 中的使用 Object.create(old object) 使用现有对象创建新对象的概念以及从 http://www.codecademy.com/courses/objects-ii/3/3?curriculum_id=506324b3a7dffd00020bf661 继承对象的概念。 .
调试后, 但我的值 console.log(C.lastname) 未定义,并且 C.getname() 给了我错误。
TypeError: C.getname is not a function
为什么它会抛出错误以及在这种情况下使用 Object.create() 的优点是什么。
最佳答案
如果您想使用 .prototype
进行继承,则需要 A
和 C
是类(而不仅仅是对象)。
var A = function() {
this.name = 'h';
this.lastname = 'n';
this.address = 'B';
}
A.prototype.getname = function() {
console.log(this.name);
};
var a = new A();
console.log(a.getname()); // h
var C = function() {};
C.prototype = new A();
var c = new C();
console.log(c.lastname); // n
console.log(c.getname()); // h
使用 Object.create 的一个显着优势超过Object.prototype对于继承来说(如此处所示),通过 Object.create 您可以使用简单的对象(而不是类)。
为了更好地理解使用 Object.create 的优点,请参阅 @FelixKling 对 similar question 的接受答案...
关于javascript - 在 Javascript 中使用创建与原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091608/