OOP Javascript vs object literal

时间:2015-07-08 04:02:53

标签: javascript oop

我发现自己很少会使用OOP,我的意思是这样的

function Person(name){
return this.name = name;
}

Person.prototype.dateOfBirth = function(){
//some stuff here
}

var John = new Person('John');
console.log(John.dateOfBirth);

也许我没有构建框架或其他什么,但有时候我喜欢使用对象文字对方法进行分组,而不是像

    var John = {
    name:'John',
    dateOfBirth: function(){
    // return etc
    }
    }

John.dateOfBirth();

也许是因为JS是一种客户端语言所以OOP是多余的,你们可以分享一下你使用JS的OOP经验吗?我学习了基本的原型继承和JS的推进对象,但我还没有找到任何用例。

1 个答案:

答案 0 :(得分:1)

查看揭示模块模式,您可以在其中控制暴露的内容和不暴露的内容。我认为它提供了OOP希望的公共/隐私控制。

This blog post is a good example

var Person = (function() {

  var name = "default";

  function dateOfBirth() {
    privateBirthCalculation(); //can only be invoked inside of the scope
    console.log( 'dateOfBirth' );
  }

  function privateBirthCalculation() {
    console.log( 'my private method' );
  }

  // explicitly return public methods and properties when this object is instantiated
  return {
    dateOfBirth : dateOfBirth,
    name: name
  };

})();
相关问题