我正在研究一种扩展方法,用于在JavaScript中创建对象和函数的子类型。我正在努力了解这两条线的不同之处:
我能否解释一下幕后实际发生的事情?
我的理解是当我传入一个对象时,如果我使用'new p();'调用的构造函数可能不存在。它是否正确?是否有办法合并任何此代码?
function extend(p) {
if (p == null) throw TypeError();
var f = function() {},
t = typeof p;
if( t === 'object' ) {
f.prototype = p;
f.prototype.constructor = f;
return new f();
} else if( t === 'function' ) {
f.prototype = new p();
f.prototype.constructor = f;
return f;
} else {
throw TypeError();
}
}
// ==========================
var Person = {
firstName: 'John',
lastName: 'Doe'
};
console.log( 'Person: ', Person );
var Employee = extend( Person );
Employee.prototype = {
employeeID: 0
}
console.log( 'Employee: ', Employee );
var Manager = extend( Employee );
Manager.prototype.fireEveryone = function() {
alert( 'Everyone is fired!!!!' );
}
console.log( 'Manager: ', Manager );
由于
答案 0 :(得分:0)
虽然我也急切地期待看到回答这个问题的答案,但我建议你看一下ECMAScript 5中引入的新继承/ OOP机制,我认为就JavaScript来说更有凝聚力。关注。
更多信息:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperties https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create