简体   繁体   English

你如何用JavaScript制作课程?

[英]How do you make classes in JavaScript?

How do you guys make "classes" in JavaScript!? 你们是如何用JavaScript制作“课程”的?

I am using: 我在用:

function classFoo()
{
   var classLevelVariable = 0;

   this.classFunction = function()
   {
      alert("The classFunction has been called.");
      classFunction2(); //Crash.  classFunction2 is "undefined."  
   }

   this.classFunction2 = function()
   {
      alert("classFunction2 called.");
   }
}

I never was able to get constructors to work. 我从来没有能够让施工人员工作。 Tried 试着

this.New = function(arguments)

Which worked once, but not in a second class. 哪个工作过一次,但不是在第二个班级。 So, I have now given up on those entirely, using my own "Initialize" functions which act as constructors. 所以,我现在已经完全放弃了这些,使用我自己的“初始化”函数作为构造函数。

The weirdness with it working once, but not twice, makes me think typographical errors between the two classes... but I think in 19 years of coding, that that probably isn't it. 它工作一次但不是两次的奇怪使我觉得两个类之间的印刷错误...但我认为在19年的编码中,可能不是它。

I'm using Chrome's debugger, and I am not receiving any errors besides the second function being undefined when being called. 我正在使用Chrome的调试器,除了第二个函数被调用时,我没有收到任何错误。

Javascript does not use class-based inheritance . Javascript不使用基于类的继承 So, you can't make classes in Javascript, except to emulate them using workarounds that are IMHO clumsy and complicated. 因此,您不能在Javascript中创建类,除非使用IMHO笨拙且复杂的变通方法来模拟它们。

Javascript is a prototypal language. Javascript是一种原型语言。 Using the new keyword creates a new object based on the prototype property of the constructor object. 使用new关键字基于构造函数对象的prototype属性创建一个新对象。

You can get an idea how you might use prototypal inheritance to instantiate a new object based on a prototypal object here: http://javascript.crockford.com/prototypal.html 您可以在此处了解如何使用原型继承来基于原型对象实例化新对象: http//javascript.crockford.com/prototypal.html

I feel that your original rant (see question's revision history) deserves a response. 我觉得你原来的咆哮(见问题的修订历史)值得回应。 It's very much against the spirit of programming and computer science, in my opinion, to declare a language broken merely because you can't make it go . 在我看来,这非常违背编程和计算机科学的精神,仅仅因为你无法实现它而宣称一种语言被破坏

Please pardon me if I offend you when I say that I'm surprised that they can give CS degrees out to people with such paradigmatic ignorance. 请原谅我,当我说我很惊讶他们可以给那些具有这种范式无知的人提供CS学位时,我会得罪你。 When I went to school, which was only about 5 years ago, I did my assignments in 6 different languages: MIPS, Verilog, Scheme, Java, C/C++ and Python. 当我上学时,大约5年前,我用6种不同的语言完成了我的作业:MIPS,Verilog,Scheme,Java,C / C ++和Python。 We used many paradigms, including functional and OOP but other styles as well. 我们使用了许多范例,包括功能和OOP,但也包括其他风格。 If you were not exposed to these different perspectives, none of which are new, your education is not complete. 如果您没有接触到这些不同的观点,其中没有一个是新的,那么您的教育就不完整。

Has it occurred to you that what you consider to be canonical OOP is merely one formulation of the OOP principles ? 您是否认为您认为规范OOP 仅仅是OOP原则的一个表述 In Javascript objects instantiate from a "prototype," and it's not the same thing as a class. 在Javascript对象中实例化“原型”,它与类不同。 When you expect it to work like a class-based OOP language, it will not meet your expectations. 当您希望它像基于类的OOP语言一样工作时,它将无法满足您的期望。 Java and C++ are not the gold standard of OOP, nor is OOP the be-all-end-all of programming. Java和C ++不是OOP的黄金标准,OOP也不是所有编程的全部。

When one considers the amazing apps that have been written in Javascript in the past 3-5 years, it's amazing that a person can make a statement like this: 当人们考虑过去3 - 5年内用Javascript编写的令人惊叹的应用程序时,一个人可以做出这样的声明真是太神奇了:

One would think we would apply our best coding practices over the last six decades into it. 人们会认为我们会在过去的六十年里将最好的编码实践应用到其中。 No. Of course not. 不,当然不。 What do we have? 我们有什么? Functions inside of functions... some weird bastardization of classes. 函数内部的函数......类的一些奇怪的混蛋。 Complete with no consistency... 完全没有一致性......

To say that, despite the brilliant achievements made by teams of brilliant Javascript developers, the language is broken because you have difficulty understanding it is, well, astonishing. 要说这一点,尽管杰出的Javascript开发团队取得了辉煌的成就,但语言被打破了,因为很难理解它是,令人惊讶的。

Please consider that, instead of the language being flawed, you may not presently possess the perspective necessary to understand it. 请注意,您可能目前没有理解它所必需的视角,而不是语言存在缺陷。


PS, You mentioned that you are "using JavaScript to AVOID FLASH!" PS,你提到你“使用JavaScript来避免闪存!” It seems like you have a very poor strategy for ascertaining facts, since Javascript and Actionscript both implement the same spec: ECMAScript. 由于Javascript和Actionscript都实现了相同的规范:ECMAScript,因此您似乎有一个非常糟糕的策略来确定事实。

JavaScript is a prototype based programming language. JavaScript是一种基于原型的编程语言。 The concept of a class does not exist or the concept of a class is the same as an object. 类的概念不存在或类的概念与对象相同。 It's quite different from say the Java programming language. 它与Java编程语言完全不同。 Do not be fooled by thier names, the similaries end there. 不要被他们的名字所迷惑,这些相似之处就在那里。

I asked this question I while back. 我回来时问了这个问题 I got an answer with a nice link to these presentation slides by John Resig. 我得到了一个答案,其中包含了John Resig对这些演示幻灯片的一个很好的链接。 Look though that and see if it helps with understanding JavaScript and prototype chains. 看一下,看看它是否有助于理解JavaScript和原型链。

Here is a good article on sitepoint.com about Object Oriented Programming in JavaScript. 是一篇关于sitepoint.com的关于JavaScript中面向对象编程的好文章。

This one on javascriptkit.com is more straightforward. 这个javascriptkit.com上更直接。

You can use a function to creates an object set its properties and functions like this: 您可以使用函数创建一个对象集,其属性和函数如下:

person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
    this.state = "running"
    this.speed = "4ms^-1"
}

or use constructors: 或使用构造函数:

function person(name,height,speed){
    this.name = name;
    this.height = height;
    this.speed = speed;
}

var p1=new person('tom', '6ft','15kmph');

alert(p1.height);

or you can use prototyping to extend objects: 或者您可以使用原型来扩展对象:

person.prototype.sayHello = function(){alert("Hi, I'm " + name;}

var p2 = new person('sam', '5.9ft', '12kmph');
p2.sayHello();//alert-> Hi, I'm sam

more in-depth details are on the linked pages. 链接页面上有更详细的信息。

JavaScript is a Prototyping Language , so things are a little different. JavaScript是一种原型语言 ,因此情况略有不同。

Here is a code snippet to explain: 这是一个代码片段来解释:

(function(){ // create an isolated scope
    // My Object we created directly
    var myObject = {
        a: function(x,y) {
            console.log('a');
        },
        b: function(x,y) {
            console.log('b');
            this.a(x,y);
        }
    };
})();

(function(){ // create an isolated scope

    // Create a Object by using a Class + Constructor
    var myClass = function(x,y) {
        console.log('myClass: constructor');
        this.b(x,y);
    };
    myClass.prototype = {
        a: function(x,y) {
            console.log('myClass: a');
        },
        b: function(x,y) {
            console.log('myClass: b');
            this.a(x,y);
        }
    };

    // Define a function that should never inherit
    myClass.c = function(x,y) {
        console.log('myClass: c');
        this.a(x,y);
    };

    // Create Object from Class
    var myObject = new myClass();
    // Will output:
    // myClass: constructor
    // myClass: b
    // myClass: a

    // Define a function that should never inherit
    myObject.d = function(x,y) {
        console.log('myObject: d');
        this.a(x,y);
    };

    // Test the world is roung
    console.log(typeof myClass.c, 'should be undefined...');
    console.log(typeof myClass.d, 'should be function...');
})();

(function(){ // create an isolated scope
    // If you are using a framework like jQuery, you can obtain inheritance like so

    // Create a Object by using a Class + Constructor
    var myClass = function(x,y) {
        console.log('myClass: constructor');
        this.b(x,y);
    };
    myClass.prototype = {
        a: function(x,y) {
            console.log('myClass: a');
        },
        b: function(x,y) {
            console.log('myClass: b');
            this.a(x,y);
        }
    };

    // Create new Class that inherits
    var myOtherClass = function(x,y) {
        console.log('myOtherClass: constructor');
        this.b(x,y);
    };
    $.extend(myOtherClass.prototype, myClass.prototype, {
        b: function(x,y) {
            console.log('myOtherClass: b');
            this.a(x,y);
        }
    });

    // Create Object from Class
    var myOtherObject = new myOtherClass();
    // Will output:
    // myOtherClass: constructor
    // myOtherClass: b
    // myClass: a
})();

(function(){ // create an isolated scope
    // Prototypes are useful for extending existing classes for the future
    // Such that you can add methods and variables to say the String class
    // To obtain more functionality
    String.prototype.alert = function(){
        alert(this);
    };
    "Hello, this will be alerted.".alert();
    // Will alert:
    // Hello, this will be alerted.
})();

There are libraries to help with this such as: 有图书馆可以帮助解决这个问题,例如:

通过使用Prototype javascript框架。

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

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