gpt4 book ai didi

javascript - 在 Javascript 中使用创建 vs 原型(prototype)

转载 作者:行者123 更新时间:2023-11-29 21:46:16 25 4
gpt4 key购买 nike

我是 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 书中接受了使用 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 进行继承,则需要AC 是类(而不仅仅是对象)。

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 中使用创建 vs 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31091608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com