简体   繁体   English

了解Crockford的无类OOP实现

[英]Understanding Crockford's classless OOP implementation

I have been reading about the different ways to do OOP in JS. 我一直在阅读有关在JS中进行OOP的不同方法。

Douglas Crockford has an interesting approach in which he doesn't appear to use delegation at all. Douglas Crockford有一种有趣的方法,他似乎根本不使用授权。 Instead, to me it appears that he purely utilizes object concatenation as his inheritance mechanism, but its kind of hard for me to tell whats going on and I'm hoping someone can help. 相反,对我而言,他似乎纯粹利用对象连接作为他的继承机制,但是我很难说出最新情况,我希望有人可以提供帮助。

Here is an example that Crockford gives in one of his talks. 以下是克罗克福德在其中一次会谈中提出的一个例子。

function constructor(spec) {
  let {member} = spec,
      {other}  = other_constructor(spec),
      method   = function () {
        // accesses member, other, method, spec
      };

  return Object.freeze({
      method,
      other
  });
}

And here is an example from a gist 以下是一个要点的例子

function dog(spec) {

  var { name, breed } = spec,
      { say }   = talker({ name }),
      bark = function () {

        if ( breed === 'chiuaua' ) {
          say( 'Yiff!' );
        } else if ( breed === 'labrador' ) {
          say('Rwoooooffff!');
        }

      };

  return Object.freeze({
    bark,
    breed
  });

}

function talker(spec) {

  var { name } = spec;
  var say = function(sound) {
        console.log(name, "said:", sound)
      }

  return Object.freeze({
    say
  });

}

var buttercup = dog({ name: 'Buttercup', breed: 'chiuaua' });

I'm confused about a few things. 我对一些事感到困惑。

I have never seen object literals used this way before. 我以前从未见过以这种方式使用的对象文字。

  • He doesn't specify key-value pairs and instead just comma separates strings. 他没有指定键值对,而只是逗号分隔字符串。
  • he uses them on the left hand of an assignment 他在任务的左边使用它们

Additionally, what are the advantages provided by freezing the object he returns? 另外,冻结他返回的物体有什么好处?

Where he doesn't specify key-value pairs and instead just comma separates strings he's taking advantage of an ES6 feature that converts the variable names of the values into string object keys for you . 他没有指定键值对,而只是逗号分隔字符串,他利用ES6功能将值的变量名称转换为字符串对象键

{ bark, breed }

is the equivalent of: 相当于:

{ bark: bark, breed: breed }

The advantage of freezing an Object is immutability. 冻结对象的优点是不变性。 Once an object is frozen it's properties can't be changed. 对象冻结后,其属性无法更改。

This is good because it helps avoid some common errors, like trying to change a non-existent property due to misspelling, and stops you (and other coders) redefining or adding methods and properties to the object after it's been created. 这很好,因为它有助于避免一些常见错误,例如由于拼写错误而尝试更改不存在的属性,并阻止您(和其他编码人员)在创建对象后重新定义或添加方法和属性。

EDIT: Another ES6 feature demonstrated here is destructuring . 编辑:这里演示的另一个ES6功能是解构

var { name, breed } = spec;

is the equivalent of: 相当于:

var name = spec.name,
    breed = spec.breed;

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

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