Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created October 31, 2022 20:54
Show Gist options
  • Select an option

  • Save ProfAvery/40d8dacecf678ae03069904f3896f577 to your computer and use it in GitHub Desktop.

Select an option

Save ProfAvery/40d8dacecf678ae03069904f3896f577 to your computer and use it in GitHub Desktop.
CPSC 349 - Objects in JavaScript
#!/usr/bin/env node
class Dog {
constructor (name) {
this.name = name
}
speak () {
return `${this.name}: bark!`
}
}
class Chihuahua extends Dog {
speak () {
return `${this.name}: yip!`
}
}
const kennel = [new Dog('Duke'), new Chihuahua('Charlie')]
for (const dog of kennel) {
console.log(dog.speak())
}
#!/usr/bin/env node
function Dog (name) {
this.name = name
}
Dog.prototype.speak = function () {
return `${this.name}: bark!`
}
function Chihuahua (name) {
Dog.call(this, name)
}
Chihuahua.prototype.speak = function () {
return `${this.name}: yip!`
}
const kennel = [new Dog('Duke'), new Chihuahua('Charlie')]
for (const dog of kennel) {
console.log(dog.speak())
}
#!/usr/bin/env node
function Dog (name) {
return {
name,
speak: function () {
return `${name}: bark!`
}
}
}
function Chihuahua (name) {
const self = Dog(name)
self.speak = function () {
return `${self.name}: yip!`
}
return self
}
const kennel = [Dog('Duke'), Chihuahua('Charlie')]
for (const dog of kennel) {
console.log(dog.speak())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment