鉴于以下代码(jQuery模式,我想):
function child(){
return new child.methods.init();
}
child.methods = child.prototype = {
init: function(){
return this;
},
test: function(){
console.log('test');
return this;
}
}
//this code doesn't work
child.methods.prototype = {
test1: function(){
console.log('test1');
return this;
}
}
child.methods.init.prototype = child.methods;
//Using child chaining api. test() will work, but test1() will not.
child().test().test1();
我需要从其他对象继承子对象(给出简化的对象文字)。 如何从对象继承子函数模式?
答案 0 :(得分:1)
Child.method是iteself child.prototype。为什么要在child.prototype / child.methods中创建新的prototype属性。您可以根据自己的要求实现链接。
// Extend properties of existing methods/functions
function extendProperties (base, extension) {
for ( var property in extension) {
try {
base[property] = extension[property];
} catch (warning) {
}
}
}
//Creating a new child
function createChild () {
return new child;
}
//Create child function . Root function
function child () {console.log('child created')}
//Prototype. Using .methods is not required.
child.methods = child.prototype = {
init: function () {
return this;
},
test: function () {
console.log('test');
return this;
}
}
//Extend existing functions methods.
//Here we are adding a new method in object of child and adding test1.
extendProperties(child.methods, {
test1: function () {
console.log('test1');
return this;
}
})
//Achieving chaining.
createChild().test().test1()