Javascript中的类变量 [英] class variable in Javascript

查看:50
本文介绍了Javascript中的类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Javascript 中声明类变量.

How do I declare class variables in Javascript.

function Person(){
    fname = "thisfname"; //What needs to be put here
 }
alert(Person.fname) //It should alert "thisFrame"

我不想使用这种方法.

function Person(){

 }
Person.fname = "thisfname";
alert(Person.fname) //alerts "thisframe"

推荐答案

JavaScript 没有其他人所说的类.继承是通过原型设计解决的,它本质上只是在新创建的对象上创建不可删除的属性引用.JavaScript 也有简单数据对象的替代方案,即对象字面量.

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 中类"的变体应如下定义:

The variation of a 'Class' in JavaScript should be defined as such:

// 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!"'

this 引用始终指向 function 的所有者.如果您在没有 new 运算符的情况下调用 Person,所有者将是全局范围(窗口).如果您不使用此引用为您的实例分配属性,则这些属性将被简单地声明为变量.如果您不使用 var 语句,那么这些声明将创建不好的全局变量!

The this reference always points to the owner of the function. If you call Person without the new operator, 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 var statement, then those declarations will create global variables which are bad!

更多相关信息

如果您想向当前实例添加属性,在构造函数中使用 this 引用是极其重要的.不使用this,您只会创建一个变量(这与属性不同),并且如前所述,如果您也不使用 var 语句,则会创建全局变量.

Using the this reference 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.

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!

使用这个!

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

实际上,当您创建类的实例时,这就是在每种经典语言中都会发生的情况.但是 JavaScript 的主要区别在于它没有封装在一个漂亮的 Class 语句中.最初 JavaScript 甚至没有函数构造函数,但后来添加了,因为 SUN 要求他们希望 JavaScript 更像 Java.

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.

对象字面量

对于只携带内部数据而没有方法的对象的函数构造函数的替代方法是对象字面量.

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.

您可以使用对象字面量和 JavaScript 做的另一件事是委托,这应该是首选.

Another thing you can do with Object literals and JavaScript is delegation, which should be preferred.

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.

这篇关于Javascript中的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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