开发者

How JavaScript does OOP?

I am learning about creating objects in JavaScript. When I do this ...

var Person = {
   name: "John Doe", 
   sayHi: functio开发者_JAVA百科n() {
   alert("Hi");
   }
};

I know that I am creating an instance of a Person class, but I do not know how (or if) I can reuse that class to create another instance. What OOP features does JavaScript has? Does it have the same OO features as other languages such as Java, or Ruby? Can someone please explain how JavaScript does OOP?


In your example you are not creating an instance of a Person class. You are creating a variable named 'Person' which contains an anonymous object.

To create a class of type Person you would do:

function Person() {
   this.name = "John Doe", 
   this.sayHi =  function() {
   alert("Hi");
   }
}

var somebody = new Person();

Otherwise I think that your question is too broad and complex. There are many javascript articles and tutorials on the web (and books in the bookstores). Go and study them and if you don't understand something specific then post here.


JavaScript does not use classes. It uses prototyping. There are multiple ways of creating new objects.

You could do:

var john = Object.create(Person);

Or you could use the new keyword:

function Person() = {
   this.name = "John Doe", 
   this.sayHi = function() {
     alert("Hi");
   }
};

var john = new Person();

For more information read:

  • http://javascript.crockford.com/inheritance.html
  • http://www.w3schools.com/js/js_objects.asp
  • http://javascript.crockford.com/prototypal.html
  • http://mckoss.com/jscript/object.htm


Crockford has some good explanations here etc.


There are several good online sources to read:

  1. McKoss
    • On Objects
  2. Crockford
    • On Inheritance
  3. JavaScript Tutors
    • On Prototyping
    • On Objects
  4. Looney
  5. SitePoint
    • Object Oriented Programming I
    • Object Oriented Programming II


Check out Oran Looney's article on this: http://oranlooney.com/classes-and-objects-javascript/

He has several good Javascript articles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜