原型和非原型方法? [英] Prototyped and a non-prototyped method?

查看:168
本文介绍了原型和非原型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,JavaScript中的prototyped和非原型方法有什么不同?非常感谢任何帮助。

I was wondering, what is the diferrence between a prototyped and a non-prototyped method in JavaScript? Any help is deeply appreciated.

推荐答案

非原型方法将在类的每个实例中占用内存。

A non-prototyped method will take up memory in every instance of the class.

它也将(假设它在类构造函数的范围内声明)可以访问在该范围内声明的任何其他私有变量(或方法)。

It will also (assuming it's declared in the scope of the class constructor) have access to any other private variables (or methods) declared in that scope.

例如,这将为每个对象创建一个函数实例,该函数可以访问 myVar

For example, this will create an instance of the function per object, and that function can access myVar:

function MyObject() {
     var myVar;
     this.func = function() { ... };
};

在这种情况下,对象的每个实例之间只共享一个函数实例,但它将无法访问 myVar

and in this case there's only one instance of the function shared between every instance of the object, but it will not have access to myVar:

function MyObject() {
     var myVar;
};

MyObject.prototype.func = function() { ... };

这篇关于原型和非原型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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