[英]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 ). 我理解這個概念。 但是,一旦您使用下面的 function 創建了一個新的 object,那么除了使用點/下標表示法之外,您如何向該 object 添加方法和屬性。 在我看來,其中任何一種都會產生丑陋的代碼。
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
然后我需要使用以下符號嗎?
newObject.method1 = function(){}
newObject.cnt = 1;
...
有沒有其他人覺得這是向 object 添加屬性和方法的丑陋方式?
我知道我可以在技術上傳遞一個 function,我想為其設置原型,以及所有方法和變量。
我或多或少試圖了解 Crockford 打算如何使用 function。
var prototypeForNewObject = {
method: function (x) { ... },
prototypeProperty: 42
};
var newObject = Object.create(prototypeForNewObject);
// Adding an instance property
newObject.cnt = 1;
而不是使用 Crock 的版本,我將使用包含可選propertiesObj
參數的完整 EcmaScript 5 簽名。 請參閱https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
您可能會在該鏈接中找到信息豐富的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.