【发布时间】:2013-09-12 09:58:03
【问题描述】:
我正在尝试创建一个类似于backbone.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();
这在大多数浏览器中都可以正常工作,但是 IE8 在以下行抛出 Object expected 错误:
var bar = new ExtendedView({message: "hello"}).render().foo();
没有比这更有用的信息了...谁能告诉我为什么会这样?
【问题讨论】:
-
我已经把这个分箱了:jsbin.com/OgUwixa/2/edit。当我在 IE8 中运行它时,出现错误:
Object doesn't support this property or method在runner.min.js中的这一行:l.postMessage("console",{method:"_raw"===b?c.shift():b,args:"_raw"===b?d.slice(1):d})。意味着 while ,您在脚本的 while 循环中描述了一个函数。但这并不可取。但是,我无法找出为什么 IE8 不理解它。 Mozilla 和 chrome 理解代码没有问题。 -
@TheDarkKnight 我认为该错误与 JSBin 本身有关,与此代码无关。
标签: javascript internet-explorer internet-explorer-8 prototype