gpt4 book ai didi

Javascript:如果不用定义原型(prototype)方法也能实现继承,为什么还要使用定义原型(prototype)方法来继承?

转载 作者:行者123 更新时间:2023-12-02 14:03:17 24 4
gpt4 key购买 nike

我提到了this问题/答案来理解原型(prototype)继承。

我知道要扩展一个方法,我们需要定义 Person.prototype.getName在基类中。这样在子类中它可以被称为 myCustomer.sayMyName();

答案中的代码可总结如下:

  function Customer(name) {
this.firstName = name;
};
function User() {

}

Customer.prototype.hi = function() {
console.log('Test method of parent');
}

User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();

但问题是,如果我可以使用以下语法调用相同的为什么我应该使用原型(prototype)

我的代码:

function Customer(name) {
this.firstName = name;
this.hi= function() {
console.log('Test method of parent');
}
};
function User() {

}
User.prototype = new Customer('shaadi');
var myUser = new User();
myUser.hi();

我可以使用parent的方法而不需要定义Customer.prototype.hi ,那么为什么/何时应该 Customer.prototype.hi会被使用吗?

如果两种解决方案都可以让我访问父级的方法,为什么我应该选择前者?

最佳答案

这是为了内存使用..

在第二个示例中,对象的每个实例都将拥有自己的函数 hi() 副本..

通过将函数 hi() 放在原型(prototype)上,该函数就只有一个实例。如果创建了数千个这样的对象,则可以节省大量内存使用量。

关于Javascript:如果不用定义原型(prototype)方法也能实现继承,为什么还要使用定义原型(prototype)方法来继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40238002/

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