Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Objects created by userFactory can access sharePublicMessage method #4

Open
abhaasgoyal opened this issue May 20, 2020 · 1 comment

Comments

@abhaasgoyal
Copy link

abhaasgoyal commented May 20, 2020

cs-bin-solutions/oop.js

Lines 181 to 188 in 20de7d4

function adminFactory(name, score) {
const admin = new userFactory(name, score);
admin.type = 'Admin';
return admin;
}
/* Put code here for a method called sharePublicMessage*/
userFunctionStore.sharePublicMessage = () => console.log('Welcome users!');

Above issue is with respect to Extension Question for - http://csbin.io/oop
The code does not prevent userFactory to access sharePublicMessage method.. Instead the solution should be to use Object.create in adminFactory function:

function adminFactory(name, score) {
  // Put code here
  let newAdminObj = userFactory(name,score);
  newAdminObj = Object.create(adminFunctionStore);
  newAdminObj.type = "Admin";
  return newAdminObj;
}

// Put code here for a method called sharePublicMessage

adminFunctionStore.sharePublicMessage = () => console.log("Welcome users!")
@samskito
Copy link

samskito commented Dec 8, 2020

@abhaasgoyal You are right saying that the userFactory have access to sharePublicMessage. But your solution is incorrect, you override the newAdminObj. This new object now doesn't have the properties of userFactory (Both name and score will be undefined).

// This part is right:
adminFunctionStore.sharePublicMessage = () => console.log("Welcome users!") 

Correct me if I'm wrong here, but the correct way should be to have both prototypes accessible to the object returned by the adminFactory. The way I did it was to create an object with the admin prototype, merge them and assign the new object as the new prototype of the returned object. This way we have all the methods in both function stores and the properties defined in userFactory.

function adminFactory(name, score) {
  const admin = new userFactory(name, score)
  const withAdminMethods = Object.create(adminFunctionStore)
  Object.assign(Object.getPrototypeOf(withAdminMethods), Object.getPrototypeOf(admin))
  Object.setPrototypeOf(admin, withAdminMethods)
  admin.type = 'Admin'
  return admin
}

It is not an ideal solution but it works.

Intersting links:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants