ruby与javascript面向对象编程的比较

原文: http://howtonode.org/object-graphs-3

作者分析了ruby与javascript两者在面向对象模式的区别,作者用图形表达这两者在面向对象模式上的区别,值得一看。这里只摘取重点部分,有兴趣的读者可看原文。
Ruby
先来看一个简单的字符串:
animal = "cat"

对象图如下:
ruby与javascript面向对象编程的比较_第1张图片
引用
Notice that every object has a class. Our string is of class String which inherits from the class Object. It's class String is of class Class which inherits Module and then Object.


再来看JavaScript
var animal = "cat";

ruby与javascript面向对象编程的比较_第2张图片
引用
Remember that you can simulate classes in JavaScript using constructor + prototype pairs. That's just what the built-in object types do. The prototypes are objects and thus inherit directly from Object.prototype and the constructors are functions and inherit from Function.prototype.


对象私有方法,注意这里说的是对象,而不是类。类的私有方法在类的声明中用private修饰。而对象私有方法是指一个对象的方法相对同类的其它对象是私有的。如下代码:
animal = "cat" #animal对象已被创建
def animal.speak #在animal对象已被创建后,可赋于其新的方法,该方法不能被同类的其它对象共享,所以是私有的
  puts "The #{self} says miaow"
end
animal.speak
puts animal.upcase

ruby与javascript面向对象编程的比较_第3张图片
引用
Notice that it injected a new anonymous class directly in front of the object and put the new method there for you. This class is hidden though. If you call the animal.class() then you'll get a reference to String directly.


来看javascript
var animal = /cat/;
animal.speak = function speak() {
  console.log("The " + this + " says miaow");
};
animal.speak();
animal.test('caterpiller');

可以看到实现方式与 ruby相类似。
ruby与javascript面向对象编程的比较_第4张图片

定义类
Ruby
class Dave
end

ruby与javascript面向对象编程的比较_第5张图片

Javascript
function Dave() {}

ruby与javascript面向对象编程的比较_第6张图片

类方法
ruby
# Make a parent class
class Person
  # with an instance method
  def greet
    puts "Hello"
  end
  # and a class method.
  def self.create
    self.new
  end
end

# Create a subclass
class Dave < Person
end
# and test it.
puts Dave.create
puts Dave.new
Dave.create.greet

ruby与javascript面向对象编程的比较_第7张图片
引用
You see that it inserted a new anonymous class in the chain to store the create method


javascript
// Make a parent class
function Person() {}
// with an instance method
Person.prototype.greet = function greet() {
  console.log("Hello");
}
// and a class method.
Person.create = function create() {
  return new this();
};

// Create a subclass
function Dave() {}
Dave.__proto__ = Person;
Dave.prototype.__proto__ = Person.prototype;
// and test it.
console.log(Dave.create());
console.log(new Dave);
Dave.create().greet();


引用
Here we make the constructor inherit from it's parent constructor (so that "class methods" get inherited) and inherit the prototypes so that "instance methods" get inherited. Again there is no need for hidden classes since javascript allows storing function properties on any object.

你可能感兴趣的:(JavaScript,Ruby)