Object.create Prototype Chains

Object.create Prototype Chains

本文关键字:Chains Prototype create Object      更新时间:2023-09-26

>初始问题

昨天我读了关于 ECMAScript 5 Object.create() 的文章我想用这种方法开始在我的代码中构建原型链,而不是设置原型及其构造函数,我喜欢你可以直接设置可写的可配置等。

我试过这样

function printobject(msg, obj) {
    if (msg) {
        document.write("<b>" + msg + "</b><br>");
        document.write("<hr><br>");
    }
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (obj[prop].toString() !== "[object Object]") {
                document.write(prop + " : " + obj[prop] + "<br>");
            }
            else {
                document.write("<b>" + prop + " : " + obj[prop] + "</b><br>");
                printobject("", obj[prop]);
            }
        }
    }
    if (msg) {
        document.write("<br><hr><br>");
    }
};
var base = {
    extend: function () { //extend this Object
        var args = Array.prototype.slice.call(arguments);
        printobject("Arguments to Extend", args)
        var that = Object.create(this, (args ? args.shift() : {}));
        var arg = args.shift() || {};
        printobject("Copy Properties to New Object", arg);
        for (var prop in arg) {
            that[prop] = arg[prop];
        }
        // Object.freeze(that);       
        return that;
    },
    create: function () { //Creates new instances of the Object
        var that = Object.create(this, {
            extend: {
                value: null,
                writable: false,
                configurable: false
            }, //sets extend and create to null so you cant create a new instance when used create ( use extend instead);
            create: {
                value: null,
                writable: false,
                configurable: false
            }
        });
        that.init.apply(that, arguments); //call init function for the new created object; 
        return that;
    },
    init: function () {
        printobject("No Initfunction supplied for New Object", this);
    } // Empty init function for fallback
}
var Human = base.extend({
    name: {
        value: "test"
    }
}, {
    init: function (name) {
        alert(name + " has been created");
        this.name = name;
    },
    walk: function () {
        alert(this.name + " walks");
    }
});
var Human1 = Human.create("test2");
//alert("Human1 - Name:" + Human1.name);
Human1.walk();
Human.walk = function () {
    alert("Walk has been overwritten")
}; //Object freezed 
Human1.walk();
Human1.create = function () {
    alert("Overwrite create");
}; //Doesnt exist in created     Object
Human1.create(); ?
  • Human中给出的方法在公羊中只存在一次吗? Human1.walk()指向它?
  • 我想知道这样做是否是正确的方法?我对 JavaScript 比较陌生。

这是jsfiddle上的代码。

首先,感谢很多让事情更清楚=)但 1:当我这样做时,实例继承自其构造函数的原型(?

 Nothing = {};
function base() {
this.inherit = function(constructor) {
    alert("inherit");
    var obj = constructor;
    obj.constructor = constructor;
    obj.prototype = this;
   return obj ;  
 }
 ;}
base.prototype = Nothing;
base.constructor = base;
var Top = new base();       
var Human = Top.inherit(function(name) {
        this.name = name;
});
var Paul = new Human("Paul");
alert(Paul.name);
alert(Paul instanceof Human); //true `

2:所以这个代码中的运算符实例没有中断,(它只适用于函数对我来说似乎很清楚)

但是这样写,Paul 仍然继承了 top 原型的 inherit() 方法我需要覆盖它但是,如果我不希望 Human 的实例继承该方法,我该怎么做?

而且我不能像可写一样设置属性描述符,除非使用 Objkect.defineproperty(?

那么使用 Object.create() 从对象继承的主要好处是什么 vs设置原型和构造器?=)

3:哦,谢谢,是的,这是定义的权利,这不是基本对象的扩展=) 谢谢你的建议=)

感谢所有的努力=)

好的,所以当我这样做时

无 = {}

base.prototype = 什么都没有;

这并不妨碍 s.o 在原型链上向上,直到 Object.prototype ?如果没有,有没有办法做到这一点?=) 会 ( 对象.创建(null); ) 这样做,

我想我必须设置

base.prototype.constructor = base;

因为否则,原型构造函数

var top = new base();

如果原型设置为 Nothing,则不会从原型链上的某个地方继承构造函数 ->

base 的顶级实例//假

更新

我现在最终以这样的方式这样做:

var base = {
// a tiny little selfmade prototypical inheritance system
// you are free to add function arguments for extending the created objects
// neither instanceof nor .constructor is featured, because "classes" are no functions
    create: function(extension,desc) {
        // instances inherit from the proto objects
        var newInst = Object.create(this.proto, desc);
        if(this.proto.childExtendable) //if Subclass allows its Children to be Extendible, do so
            newInst.extend(extension);
        if(newInst.init||this.proto.init) //4
            newInst.init()                          
        return newInst
    },
    inherit: function(props) {
        // the "class" inherits static methods from the class
        var sub = Object.create(this);
        // and the proto objects inherits from the parent proto
        sub.proto = Object.create(this.proto);
        props.protect = this.protect;
        if(props.childExtendable)
            props.extend = this.extend;
        this.extend.call(sub.proto, props);
        return sub;
    }, 
    extend: function (props) {
        for (var prop in props) {
            var propmatch = prop.match(/(.*?)__(.{1,5}?)__(.*)/)||["",prop,"",""];
            this[propmatch[1]+propmatch[3]] = props[prop];
            if(propmatch[2])
                this.protect(propmatch[1]+propmatch[3],propmatch[2]);           
        }
    },
    protect: function(prop,flags) { //with each call it toggles the given flags,  so you can protect funcitons given to the inherit function ;; //This should be available to all childs, but adding it to the base.proto, it changes Object.prototyppe ( therefore not a good idea)
        var d  = Object.getOwnPropertyDescriptor(this, prop);
        if (flags.match(/w/)){
             Ti.API.info("Setting writable for propertie " + prop + " in Object " + this + " to " + !d.writable);
             Object.defineProperty(this, prop, {writable:!d.writable});};
        if (flags.match(/c/)){
            Ti.API.info("Setting configurable for propertie " + prop + "in Object " + this);
            Object.defineProperty(this, prop, {configurable:!d.configurable});};
        if (flags.match(/e/)){
            Ti.API.info("Setting enumerable for propertie " + prop + "in Object " + this);
            Object.defineProperty(this, prop, {configurable:!d.enumerable});};
        if (flags.match(/a/)){
            Ti.API.info("Setting enumerable for propertie " + prop + "in Object " + this);
            Object.preventExtensions(this);};
   },
    init: function() {},
    proto: Object.prototype // or null, if you want
};
var Human = base.inherit({ //will be put in Human.proto
    childExtendable:true,
    init:function() {alert("Humans Init for all Instances")},
    say:function() { alert("Hi, I'm "+this.name); }
});
Human.proto.name = "default"; // You could use an argument to the inherit function
                              // I just want to make clear what happens
Ti.API.info(Object.getPrototypeOf(Function) + "a");
var paul = Human.create({ //extends this object
    name: "Paul",
    test: function() {alert("test")},
    init__wce__: function() {alert("Pauls Own Init")},
    say__w__ : function() { alert("Hi, I'm" + this.name + "s Own Function")}
});
paul.name = "Paul";           // and again, the create function might do it for you
paul.say = function() {alert("Pauls say is overwritten")} // define init without __wce__ and it will be overwritten
paul.say(); // -> "Hi, I'm Paul"

只要有人在乎
但是,jsfiddle不会运行这个,Titanium会按预期执行所有操作也许是一些严格的模式(??

人类给出的方法在公羊中只存在一次吗?

是的。

而 Human1.walk() 指向它?

是的。更准确地说,Human1的原型,Human,有一个指向它的属性"行走"。

我想知道这样做是否是正确的方法?我对 JavaScript 比较陌生。

我会说不,因为它过于复杂,而且部分错误。

  • 人类实例的原型链包括base .这很奇怪,您需要覆盖每个实例的创建和扩展方法。通常的方法是"类"包含一个"原型"属性,它们的实例从该属性继承。
  • 您的模式破坏了instanceof运算符,尽管这可能是一个小问题。
  • 扩展方法令人困惑。它不会扩展对象本身,而是创建一个从它继承的新对象,并在其上设置属性和属性描述符。更好地实现同一件事:

base.inherit = function(descs, props) {
    // creates a new object inheriting from this
    var that = Object.create(this, descs); // will even work when undefined
    if (props)
        for (var prop in props)
            that[prop] = props[prop];
    // Object.freeze(that);       
    return that;
};

对于扩展的问题:

base.prototype = Nothing​;
base.constructor = base;

是相当没用的。首先,默认情况下,任何函数的"prototype"属性都是(几乎)空的对象,直到你覆盖它。无需将其设置为 nothing :-)

"构造函数"属性通常是原型属性。它将被所有实例继承,指向 thei 构造函数。您只需在覆盖函数的"原型"属性时显式设置它 - 并且不应在函数本身上设置"构造函数"属性。

(续:)我更喜欢这样的解决方案:

var base = {
// a tiny little selfmade prototypical inheritance system
// you are free to add function arguments for extending the created objects
// neither instanceof nor .constructor is featured, because "classes" are no functions
    create: function([desc]) {
        // instances inherit from the proto objects
        return Object.create(this.proto, [desc]);
    },
    inherit: function([props]) {
        // the "class" inherits static methods from the class
        var sub = Object.create(this);
        // and the proto objects inherits from the parent proto
        sub.proto = Object.create(this.proto);
        [Object.extend(sub.proto, props);]
        return sub;
    },
    proto: Object.prototype // or null, if you want
};
var Human = base.inherit();
Human.proto.name = "default"; // You could use an argument to the inherit function
                              // I just want to make clear what happens
Human.proto.say = function() { alert("Hi, I'm "+this.name); };
var paul = Human.create();
paul.name = "Paul";           // and again, the create function might do it for you
paul.say(); // -> "Hi, I'm Paul"

这样,paul继承自Human.proto继承base.proto Object.prototypenull。并且Human继承自base,即你可以很容易地用Human.inherit()构建一个"子类"。

是否要使用属性描述符绝对是您的选择。无论在何处创建并扩展它,都可以使用Object.defineProperties(或Object.create的第二个参数)以及Object.extend(通常的复制方法)。

使用 Object.create() 继承自 Objects 与设置原型和构造器的主要好处是什么?

这是一个设计选择。 Object.create不会在构建的对象上调用 [构造函数] 函数。有关更多信息,请参阅使用 "Object.create" 而不是 "new" 或 了解 Object.create() 和 new SomeFunction() 之间的区别。

base.prototype = {}; 不会阻止 s.o 在原型链上向上,直到 Object.prototype?

是的。空对象(由文字创建)在其链中仍有Object.prototype。执行此操作的唯一方法是Object.create(null)(不能使用new填充)。

以为我必须设置base.prototype.constructor = base;

不是在这种情况下。有一个function base(){...},将其"prototype"属性设置为{constructor: base}绝对不会改变任何东西(除了现在可枚举的"构造函数") - 每个函数都有这样一个默认的原型对象,包括"构造函数"。

因此,仅当您需要用新对象覆盖"prototype"属性时,就像让它从另一个函数的原型继承时发生的那样,您可以添加以下便利属性:MySubClass.prototype = Object.create(MyClass.prototype, {constructor:{value:MySubClass}});

否则。。。

什么都不会发生。原型对象上的"构造函数"属性对于任何语言功能(如instanceof)都是必需的,并且很少使用。很可能什么都没有坏。