I have source code like this
const item = function(p) {
let model;
p.setup = function() {
}
}
I am not sure how should I call this class
? function component
?
What I want to do is add my function to this and call this function from outside.
const item = function(p) {
let model;
p.setup = function() {
}
function nextGame(){
console.log("test");
}
}
item.nextGame(); // error
However it doesn't work.
I am not familiar this style of javascript.
How should I add the function to this(is it class??) and call??
CodePudding user response:
What you describe and demonstrate in your snippet javascript is an anonymous function, you could even say that it is a functional variable.
To access methods using dot notation, you need to create a class (or javascript object).
example using the keyword 'class':
class MyClass
{
var name;
var lastName;
constructor(_name, _lastname)
{
this.name = _name;
this.lastName = _lastname;
}
sayMyName()
{
window.alert(`${this.name} ${this.lastname}`);
}
}
Now create an instance of this class. Like this:
const myName = new MyClass("John", "Doe");
and now call with the method of your class using notation. Like this:
myName.sayMyName();
CodePudding user response:
class Item {
// private field for whatever
// got passed to the constructor.
#value;
constructor(value) {
this.#value = value;
}
// prototypal methods with access to
// private fields and private methods.
setup() {
// do something with `this.#value`
console.log(this.#value);
}
nextGame() {
console.log("next game");
}
}
const item = new Item("OP's mysterious `p` value");
console.log({ item });
console.log('item.setup() ...');
item.setup();
console.log('item.nextGame() ...');
item.nextGame();
.as-console-wrapper { min-height: 100%!important; top: 0; }
CodePudding user response:
For object-oriented programming in javascript there are a few methods, as mentioned in the comments.
1. Factory Function
A factory function is a simple approach, as it just creates and returns an object.
function Item(model) {
const item = {
model,
nextGame: () => { console.log('test') }
}
return item
}
const itemInstance = Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)
2. Constructor Function
Uses the new keyword to create an instance of the defined object type. It utilizes the function's prototype, which is accessible on all instances of the type.
function Item(model) {
this.model = model;
}
Item.prototype.nextGame = () => { console.log('test') }
const itemInstance = new Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)
3. Class
You could also use a Class. Classes in javascript are provided as an abstraction of functions.
class Item {
constructor(model) {
this.model = model
}
nextGame() {
console.log('test')
}
}
const itemInstance = new Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)