Javascript Javascript中的类变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3641229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
class variable in Javascript
提问by alter
How do I declare class variables in Javascript.
如何在 Javascript 中声明类变量。
function Person(){
fname = "thisfname"; //What needs to be put here
}
alert(Person.fname) //It should alert "thisFrame"
I don't want to use this approach.
我不想使用这种方法。
function Person(){
}
Person.fname = "thisfname";
alert(Person.fname) //alerts "thisframe"
回答by BGerrissen
JavaScript does not have classes like others have said. Inheritance is resolved through prototyping which in essence does nothing more than create non-deletable property references on a newly created object. JavaScript also has alternatives for simple data objects, namely object literals.
JavaScript 没有其他人所说的类。继承是通过原型设计解决的,它本质上只是在新创建的对象上创建不可删除的属性引用。JavaScript 也有简单数据对象的替代方案,即对象字面量。
The variation of a 'Class' in JavaScript should be defined as such:
JavaScript 中“类”的变体应定义如下:
// I use function statements over variable declaration
// when a constructor is involved.
function Person(name) {
this.name = name;
}
// All instances of Person create reference methods to it's prototype.
// These references are not deletable (but they can be overwritten).
Person.prototype = {
speak: function(){
alert(this.name + ' says: "Hello world!"');
}
};
var Mary = new Person('Mary');
Mary.speak(); // alerts 'Mary says: "Hello world!"'
The thisreference always points to the owner of the function. If you call Personwithout the newoperator, the owner will be the global scope (window). If you do not use this reference to assign properties to your instance, then the properties will simply be declared as variables. If you do not use the varstatement, then those declarations will create global variables which are bad!
该this引用始终指向function. 如果您在Person没有new操作员的情况下调用,则所有者将是全局范围(窗口)。如果您不使用此引用为您的实例分配属性,则这些属性将被简单地声明为变量。如果您不使用该var语句,那么这些声明将创建不好的全局变量!
more about this
更多关于这个
Using the thisreference in a constructor function is exceedingly important if you want to add properties to the current instance. Without using this, you only create a variable (which is not the same as a property) and as mentioned, if you don't use the var statement either, you create global variables.
this如果您想向当前实例添加属性,在构造函数中使用引用是非常重要的。不使用this,您只会创建一个变量(这与属性不同),并且如前所述,如果您也不使用 var 语句,您将创建全局变量。
function Person(){
name = 'Mary'
}
var p = new Person();
alert(p.name); // undefined, did not use 'this' to assign it to the instance.
alert(name); // 'Mary', boo, it created a global variable!
Use this!
用这个!
function Person(){
this.name = 'Mary'
}
var p = new Person();
alert(p.name); // 'Mary', yay!
alert(name); // undefined, yay!
Note, anything assigned to an instance through the function constructor CANNOT BE INHERITED unless you assign it to the prototype and overwrite it again in the function constructor to make it an owned property.
请注意,通过函数构造函数分配给实例的任何内容都不能被继承,除非您将其分配给原型并在函数构造函数中再次覆盖它以使其成为拥有的属性。
When you create a new instance of through a function doubling as a constructor, actually the following happens.
当您通过兼作构造函数的函数创建新实例时,实际上会发生以下情况。
pseudo code:
copy Person.prototype as person
invoke Person function on person
return person
Actually, this is what happens in every classical language when you create an instance of a class. But the main difference in JavaScript is that it's not encapsulated inside a nice Class statement. Originally JavaScript didn't even have function constructors but was added on later because SUN demanded they wanted JavaScript to be more like Java.
实际上,当您创建类的实例时,这就是在每种经典语言中都会发生的情况。但是 JavaScript 的主要区别在于它没有封装在一个漂亮的 Class 语句中。最初 JavaScript 甚至没有函数构造函数,但后来添加了,因为 SUN 要求他们希望 JavaScript 更像 Java。
Object literals
对象字面量
The alternative for function constructors for objects that carry only intrinsic data and no methods are object literals.
对于只携带内部数据而没有方法的对象的函数构造函数的替代方案是对象文字。
var Mary = {
firstName: 'Mary',
lastName: 'Littlelamb'
};
Which is the prefered way of declaring intrinsic objects rather then:
这是声明内部对象的首选方式,而不是:
// do not ever do this!
var Mary = new Object();
Mary.firstName = 'Mary';
Mary.lastName = 'Littlelamb';
With object literals in your skill set, you can create a factory pattern for intrinsic data objects using the module pattern(which is usually for singletons).
通过您的技能集中的对象文字,您可以使用模块模式(通常用于单例)为内部数据对象创建工厂模式。
var createPerson = function(firstName, lastName){
return {
firstName: firstName,
lastName: lastName
}
}
var Mary = createPerson('Mary', 'Littlelamb');
This achieves some comfortable encapsulation, but can only be used for intrinsic data objects.
这实现了一些舒适的封装,但只能用于内部数据对象。
Another thing you can do with Object literals and JavaScript is delegation, which should be preferred.
您可以使用对象字面量和 JavaScript 做的另一件事是委托,这应该是首选。
var personMethods = {
speak: function(){
alert(this.firstName + ' says: "Hello world!"');
}
};
var Mary = {
firstName: "Mary",
lastName: "Littlelamb"
};
var Peter = {
firstName: "Peter",
lastName: "Crieswolf"
};
personMethods.speak.apply(Mary); // alerts 'Mary says: "Hello world!"'
personMethods.speak.apply(Peter); // alerts 'Peter says: "Hello world!"'
Why should this be preferred? Because it keeps your objects minute and readable, even prototypical references take up memory and when using inheritance and 'subclassing' you end up with child instances that have lots of unused method references. Delegation is always better.
为什么这应该是首选?因为它使您的对象保持紧凑和可读,即使是原型引用也会占用内存,并且在使用继承和“子类化”时,您最终会得到具有大量未使用方法引用的子实例。委托总是更好。
回答by aularon
The way you mentioned is how to define class variables, the other way (inside function Person) is to define instance properties.
您提到的方式是如何定义类变量,另一种方式(内部function Person)是定义实例属性。
function Person(name){
this.name = name;
}
Person.specie = "Human";
alert(Person.specie) //alerts "Human", a class variable.
var john = new Person('John');
alert(john.name); //alerts "John", an object property.
回答by user123444555621
It is important to understand that there is no such thing as classes in JavaScript. There are some frameworks out there that simulate a classical inheritance pattern, but technically it all boils down to constructor functions and prototypes.
重要的是要了解 JavaScript 中没有类这样的东西。有一些框架可以模拟经典的继承模式,但从技术上讲,它们都归结为构造函数和原型。
So, you may want to do something like
所以,你可能想做类似的事情
PersonProto = { // the "class", or prototype
fname: "thisfname"
};
function Person() { // the constructor function
this.instanceVar = 'foo';
}
Now, connect the constructor to the prototype:
现在,将构造函数连接到原型:
Person.prototype = PersonProto;
And, voilà:
而且,瞧:
var a = new Person();
alert(a.fname);
回答by Kartikeya Sharma
You can also try this approach:
你也可以试试这个方法:
function name() {
this.name;
this.lastname;
}
name.prototype.firstName = function(name) {
this.name = name;
alert(this.name);
}
var x = new name();
x.firstName("Kartikeya");
回答by simplyharsh
function Person(){
this.fname = null;
this.lname = null;
this.set_fname = set_fname;
this.set_lname = set_lname;
this.get_name = get_name;
}
/* Another way
function Person(fname, lname){
this.fname = fname;
this.lname = lname;
this.get_name = get_name;
}*/
function set_fname(fname){
this.fname = fname;
}
function set_lname(y){
this.lname = lname;
}
function get_name(){
with (this) {
return fname + ' ' + lname;
}
}
person_obj = new Person();
person_obj.set_fname('Foo');
person_obj.set_lname('Bar');
// person_obj = new Person('Foo', 'Bar');
person_obj = get_name(); // returns "Foo Bar"
Can't think of better example.
想不出更好的例子。
回答by sweets-BlingBling
3 ways to define a variables to JavaScript class:
为 JavaScript 类定义变量的 3 种方法:
1)To define properties created using function(), you use the 'this' keyword
1) 要定义使用 function() 创建的属性,请使用 'this' 关键字
function Apple (type) {
this.type = type;
this.color = "red";
}
To instantiate an object of the Apple class, set some properties you can do the following:
要实例化 Apple 类的对象,请设置一些属性,您可以执行以下操作:
var apple = new Apple('macintosh');
apple.color = "reddish";
2) Using Literal Notation
2) 使用文字符号
var apple = {
type: "macintosh",
color: "red"}
var apple = {
类型:“macintosh”,
颜色:“红色”}
In this case you don't need to (and cannot) create an instance of the class, it already exists.
在这种情况下,您不需要(也不能)创建类的实例,它已经存在。
apple.color = "reddish";
3) Singleton using a function
3) 单例使用函数
var apple = new function() {
this.type = "macintosh";
this.color = "red";
}
So you see that this is very similar to 1 discussed above, but the way to use the object is exactly like in 2.
所以你看到这与上面讨论的 1 非常相似,但是使用对象的方式与 2 中的完全一样。
apple.color = "reddish";

