Is there a way that Javascript can mimic an object oriented language?
I'm wondering if there is a way that Javascript can mimic an object oriented language. I.e. can you mimic the ability to define customized classes/objects with properties? Since JSO开发者_如何学运维N is basically a way of javascript passing objects, I figure there must be some way to create/store objects on the client side, then reuse them? If someone can point me to a good tutorial (if it's possible to do this at all) that would be much appreciated.
Even some example code where you can dynamically create an object, then consume it using jquery would be appreciated.
Javascript is an object oriented language, it's just not a class based object system, but a prototype based one. See this article: http://en.wikipedia.org/wiki/Prototype-based_programming
I found this to be a great tutorial: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
It must be said that Javascript is object oriented, however it is prototype based, rather than class based.
Douglas Crockford is a recognized person in JavaScript community,
His talks about JS are really good. In this series he talks about advanced js including object oriented javascript.
http://video.yahoo.com/video/play?vid=111585 http://video.yahoo.com/video/play?vid=111586 http://video.yahoo.com/video/play?vid=111587
Javascript is an Object Oriented language.
JavaScript is object oriented. It's just that it's prototype-based rather than class-based.
That said, JSON is not really suitable for serializing objects with inherited properties.
The short answer is "yes". There are a couple of excellent articles at developer.mozilla.org:
- A re-introduction to JavaScript which includes its relationship to object-oriented languages
- Introduction to Object-Oriented JavaScript
If you prefer an actual book, this has been very useful for me: Pro Javascript Design Patterns
Although Javascript does not have a built-in class system (although the next version of Javascript might include this), there are many different Javascript OO Design Patterns that mimic the behavior of Classes. The Module pattern mimic's classes by allowing a Javascript object to hold both private and public members. This is achieved like so:
var Person = function() {
var firstName = "Greg";
var lastName = "Franko";
return {
getFirstName: function() {
return firstName;
},
getLastName: function() {
return lastName;
}
}
}
//Instantiate a new Person object
var greg = new Person();
//This will not work because the firstName property is private
console.log(greg.firstName);
//This will work because the getFirstName method is public
console.log(greg.getFirstName());
精彩评论