js bind 问题
class jbf {
constructor(options) {
Object.keys(options).forEach(key => {
if (typeof options[key] === 'function') {
// this[key] = options[key].bind(this);
this[key] = options[key];
} else {
this[key] = options[key];
}
});
}
}
// Define the child component object using jbf
const childComponent = new jbf({
_name: "child",
reqc: 0,
req: function(tar) {
console.log("Inside req function, this (should be parent):", this);
console.log("tar:", tar);
this.reqc++;
}
});
// Define the parent component object using jbf
const parentComponent = new jbf({
_name: "parent",
handleAction: function(action, target) {
const acfn = this[action];
console.log("Calling method from parent, this:", this);
if (typeof acfn === 'function') {
// Ensure `this` context is correct
const boundFn = acfn.bind(this);
boundFn(target); // Call the bound method
} else {
console.error(`${action} is not a function`);
}
},
printReqc: function() {
console.log("Parent reqc:", this.reqc);
console.log("Child reqc:", this.childComponent.reqc);
}
});
// Function to merge methods and properties from source to target
function mergeObjects(target, source) {
Object.keys(source).forEach(key => {
if (key.startsWith('_')) {
// Skip properties that start with an underscore
return;
}
if (typeof source[key] === 'function') {
// Ensure methods are bound to the target object
target[key] = function(...args) {
return source[key].apply(target, args);
};
} else {
// Otherwise, just copy the property
target[key] = source[key];
}
});
}
// Merge child component methods into parent component
mergeObjects(parentComponent, childComponent);
// Add childComponent to parentComponent so we can access it
parentComponent.childComponent = childComponent;
// Set up the button to trigger the action
document.getElementById('trigger').addEventListener('click', () => {
parentComponent.handleAction('req', 'testTarget');
});
// Set up the button to print reqc values
document.getElementById('printReqc').addEventListener('click', () => {
parentComponent.printReqc();
});
标签:javascript
加入收藏