克罗克福德原型继承 [英] Crockford Prototypical Inheritance

查看:58
本文介绍了克罗克福德原型继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的文章中,Douglas Crockford创建了一个函数来更接近地模拟JavaScript中的原型继承( http:/ /javascript.crockford.com/prototypal.html )。我理解这个概念。但是,一旦使用下面的函数创建新对象,除了使用点/下标表示法之外,如何向该对象添加方法和属性。在我看来,其中任何一个都会产生丑陋的代码。

In the following article, Douglas Crockford creates a function to more closely simulate prototypical inheritance in JavaScript (http://javascript.crockford.com/prototypal.html). I understand the concept. However, once you create a new object using the function below, how do you then add methods and properties to that object other than using dot/subscript notation. Either of which, in my opinion, would produce ugly code.

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

newObject = Object.create(oldObject);

我是否需要使用以下表示法?

Do I then need to use the following notation?

newObject.method1 = function(){}
newObject.cnt = 1;
...

是否有其他人认为这是添加属性和方法的丑陋方式到一个对象?

Does anyone else find this as an ugly way to add properties and methods to an object?

我明白我可以在技术上传递一个函数,我想用它设置所有方法和变量的原型。

I understand I can technically pass in a function, for which I want to set the prototype of, with all the methods and variables.

我或多或少想要了解Crockford打算如何使用该功能。

I'm more or less trying to understand how Crockford intended for that function to be used.

推荐答案

var prototypeForNewObject = {
  method: function (x) { ... },
  prototypeProperty: 42
};

var newObject = Object.create(prototypeForNewObject);

// Adding an instance property
newObject.cnt = 1;

而不是使用Crock的版本,我会使用包含可选<$的完整EcmaScript 5签名c $ c> propertiesObj 参数。请参阅 https://developer.mozilla.org/en/JavaScript/Reference/ Global_Objects / Object / create

And instead of using Crock's version, I would use the full EcmaScript 5 signature that includes an optional propertiesObj argument. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create

您可能会在该链接上找到提供信息的示例。

You might find the examples at that link informative.

这篇关于克罗克福德原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆