我正在尝试创建一个原型扩展系统,如主干.js。
我有以下代码:
var _ = {
/**
* Applies a function to each property in an object.
*
* @public
* @param {Object} obj - Object to loop through.
* @param {Function} callback - Callback to pass each property to.
* @param {*} [context] - Optionally set the context for the callback function.
*/
each: function (obj, callback, context) {
context = context || null;
if (obj.length) {
for (var i = 0; i < obj.length; i++) {
callback.call(context, obj[i], i);
}
} else {
for (var prop in obj) {
if (_.has(obj, prop)) {
callback.call(context, obj[prop], prop);
}
}
}
},
/**
* Takes properties from any number of objects and passes them to the first, properties of objects later in the arguments list take precedence.
*
* @public
* @param {Object} source - Object to recieve properties.
* @param {...Object} Zero or more objects to steal properties from
* @returns {Boolean}
*/
extend: function (source) {
var count = arguments.length;
var i = 1;
while (i < count) {
var obj = arguments[i];
_.each(obj, function (prop, key) {
source[key] = prop;
});
i++;
}
return source
},
/**
* Safely checks if object has a property incase the object's hasOwnProperty property gets overwritten.
*
* @public
* @param {Object} obj - Object to test.
* @param {String} prop - Property name to test.
* @returns {Boolean}
*/
has: function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}
var View = function(opts) {
_.extend(this, opts);
}
View.prototype = {
init: function() {},
render: function() {
return this;
}
}
View.extend = function(proto) {
var parent = this;
// Proxy the parent's constructor
var child = function() { return parent.apply(this, arguments); };
child.prototype = Object.create(parent.prototype);
_.extend(child.prototype, proto);
child.extend = View.extend;
return child;
}
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
F.prototype = o;
return new F()
}
})()
}
var ExtendedView = View.extend({
foo: function() {
console.log(this.message);
}
});
var bar = new ExtendedView({message: "hello"}).render().foo();
这在大多数浏览器中都可以正常工作,但是 IE8Object expected
在以下行抛出错误:
var bar = new ExtendedView({message: "hello"}).render().foo();
它没有给我比这更有用的信息......谁能告诉我为什么会这样?