2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Create a Method on an Object
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Create a Method on an Object
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
An objects function must be initialised within the object itself. This is demonstrated in the following code.
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
let obj = {
|
2019-07-24 00:59:27 -07:00
|
|
|
property1: 1,
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
function1: function() {
|
|
|
|
//Code to be exectued
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|
|
|
|
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
|
|
|
```javascript
|
2018-10-12 15:37:13 -04:00
|
|
|
let dog = {
|
|
|
|
name: "Spot",
|
|
|
|
numLegs: 4,
|
|
|
|
sayLegs: function() {
|
|
|
|
return "This dog has " + dog.numLegs + " legs.";
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
dog.sayLegs();
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|