定义函数原型和类属性有什么区别? [英] What is difference between define function by prototype and class property?

查看:278
本文介绍了定义函数原型和类属性有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照我的代码,

Apple按原型定义函数。

Banana是按类属性定义函数。

Follow my code,
Apple is define function by prototype.
Banana is define function by class property.

var Apple = function(){}
Apple.prototype.say = function(){
    console.debug('HelloWorld');
}
var Banana = function(){
    this.say = function(){
        console.debug('HelloWorld');
    }
}

var a = new Apple();
var b = new Banana();

a.say();
b.say();

这些有区别吗?

推荐答案

当您创建Apple的多个实例时,内存中仍然只有一个 say()的实例。但是,当您创建多个Banana实例时,最终会创建大量 say()函数的实例。

When you create more than one instance of Apple, you will still only have only one instance of say() in memory. However, when you create more than one instance of Banana, you will end up creating lots of instances of the say() function.

这就是原型节省内存的原因。您还可以避免创建和分配 say()函数的处理成本。

That's why prototypes save memory. You also avoid the processing cost of creating and assigning the say() function.

此外,如果您更改父对象的属性,如果子对象没有替换该属性,则从子对象中可以看到更改。

Also, if you change the parent object's properties, if the child does not replace that property, changes are visible from the child.

这篇关于定义函数原型和类属性有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆