最初的问题
昨天我读到了 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
仅在 ram 中存在一次?并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:所以 instanceof 运算符不会在此代码中中断,(它仅适用于函数对我来说似乎很清楚)
但是这样写,Paul 仍然从 Top 的原型继承了 inherit() 方法,我需要覆盖它但是如果我不希望 Human 的实例继承该方法,我该怎么做呢?
除了使用 Objkect.defineproperty (?) 之外,我无法设置像 wrtable 这样的属性描述符
那么使用 Object.create() 从 Objects 继承与设置原型和构造函数的主要好处是什么?=)
3:哦,谢谢,是的,这是正确的,这不是基础对象的扩展=)谢谢建议=)
感谢所有的努力 =)
回答
好的,所以当我这样做时
没有={}
base.prototype = 没有;
这不会阻止原型链向上直到 Object.prototype 吗?如果没有,有没有办法做到这一点?=) 会 ( Object.create(null); ) 这样做,
我认为我必须设置
base.prototype.constructor = base;
因为否则,原型的构造函数
var Top = new base();
如果原型设置为 Nothing ->
Top instanceof base // false
更新
我现在以这样的方式结束了它:
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 会按预期执行所有操作,也许是某种严格模式(??)