简体   繁体   English

康乐福原型 Inheritance

[英]Crockford Prototypical Inheritance

In the following article, Douglas Crockford creates a function to more closely simulate prototypical inheritance in 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.但是,一旦您使用下面的 function 创建了一个新的 object,那么除了使用点/下标表示法之外,您如何向该 object 添加方法和属性。 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?有没有其他人觉得这是向 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.我知道我可以在技术上传递一个 function,我想为其设置原型,以及所有方法和变量。

I'm more or less trying to understand how Crockford intended for that function to be used.我或多或少试图了解 Crockford 打算如何使用 function。

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

var newObject = Object.create(prototypeForNewObject);

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

And instead of using Crock's version, I would use the full EcmaScript 5 signature that includes an optional propertiesObj argument.而不是使用 Crock 的版本,我将使用包含可选propertiesObj参数的完整 EcmaScript 5 签名。 See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create

You might find the examples at that link informative.您可能会在该链接中找到信息丰富的示例。

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

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