简体   繁体   English

在JavaScript中创建类成员的最佳方法是什么

[英]what is the best way to create a class members in JavaScript

What is the Best Way To Define Object Memeber and Please Explain Why 什么是定义对象Memeber的最佳方式,请解释为什么

1 : 1st Way 1:第一道

var Obj = {
           M1 : 1,
           M2 : 2    
}

Using it like 使用它就像

 Obj.M1

2 :2nd Way 2:第二路

var Obj = function(){
 if (!(this instanceof Obj ))
            return new Obj ();
}
Obj.prototype.M1 =1 ;
Obj.prototype.M2 =2 ;

Using it Like 使用它喜欢

Obj().M1;

i mean with all that is using prototype better than defining the whole members with in these {} ? 我的意思是所有使用原型比在{}中定义整个成员更好吗?

That dependes whether you want to create multiple instances of Obj or just one. 这取决于您是要创建Obj多个实例还是仅创建一个。 Aspects from class-based object oriented languages like inheritance are only possible when you use the second way (it's not real inheritance as you know it from class-based OO languages, but it's similar). 只有在使用第二种方式时才能使用基于类的面向对象语言(如继承)的方面(它不是真正的继承,因为你从基于类的OO语言中知道它,但它是类似的)。 Generally you can compare the first way with a static class in class-based OO programming languages in case you are more familiar with them. 通常,您可以在基于类的OO编程语言中将第一种方法与静态类进行比较,以防您更熟悉它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM