Repository: sayazamurai/python-vs-javascript Branch: master Commit: 53387b23f054 Files: 5 Total size: 85.8 KB Directory structure: gitextract_4h1cm22n/ ├── LICENSE ├── README.md ├── index.html └── static/ ├── app.js └── prism-base16-atelierplateau.light.css ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Saya Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # [How to write X in both Python 3 and JavaScript (ES2015)](https://sayazamurai.github.io/python-vs-javascript/) [](https://sayazamurai.github.io/python-vs-javascript/) ================================================ FILE: index.html ================================================
Python and JavaScript are two of the most popular programming languages. If you're a Python programmer learning JavaScript, or a JavaScript programmer learning Python, this handy cheat sheet might help you.
This page is open sourced on GitHub. Pull requests are welcome!
abs# 100
print(abs(-100))
# 50
print(abs(50))
abs// 100
console.log(Math.abs(-100))
// 50
console.log(Math.abs(50))
ifsome_number = 3
# Number is 3
if some_number == 1:
print("Number is 1")
elif some_number == 2:
print("Number is 2")
elif some_number == 3:
print("Number is 3")
else:
print("?")
ifconst someNumber = 3
// Number is 3
if (someNumber === 1) {
console.log('Number is 1')
} else if (someNumber === 2) {
console.log('Number is 2')
} else if (someNumber === 3) {
console.log('Number is 3')
} else {
console.log('?')
}
x = 2
y = 3
# even
print("even" if x % 2 == 0 else "odd")
# odd
print("even" if y % 2 == 0 else "odd")
Conditional Operatorconst x = 2
const y = 3
// even
console.log(x % 2 === 0 ? 'even' : 'odd')
// odd
console.log(y % 2 === 0 ? 'even' : 'odd')
# yes
if "abc" == "abc":
print("yes")
else:
print("no")
# yes
if "abc" != "def":
print("yes")
else:
print("no")
# no
if True and False:
print("yes")
else:
print("no")
# yes
if True or False:
print("yes")
else:
print("no")
# yes
if not False:
print("yes")
else:
print("no")
# no
if 0:
print("yes")
else:
print("no")
# no
if "":
print("yes")
else:
print("no")
# no
if []:
print("yes")
else:
print("no")
# no
if None:
print("yes")
else:
print("no")
# yes
if not not not None:
print("yes")
else:
print("no")
Falsy Values// yes
if ('abc' === 'abc') {
console.log('yes')
} else {
console.log('no')
}
// yes
if ('abc' !== 'def') {
console.log('yes')
} else {
console.log('no')
}
// no
if (true && false) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (true || false) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (!false) {
console.log('yes')
} else {
console.log('no')
}
// no
if (0) {
console.log('yes')
} else {
console.log('no')
}
// no
if ('') {
console.log('yes')
} else {
console.log('no')
}
// no
if (undefined) {
console.log('yes')
} else {
console.log('no')
}
// no
if (null) {
console.log('yes')
} else {
console.log('no')
}
// yes
if (!!!null) {
console.log('yes')
} else {
console.log('no')
}
Errors# foo is not defined
try:
foo()
except NameError:
print("foo is not defined")
try...catch// foo is not defined
try {
foo()
} catch (error) {
console.log('foo is not defined')
}
break/continue# 1
# 2
# Fizz
# 4
# Buzz
for number in range(1, 101):
if number == 3:
print("Fizz")
continue
if number == 5:
print("Buzz")
break
print(number)
lensome_string = "abcd"
# 4
print(len(some_string))
lengthconst someString = 'abcd'
// 4
console.log(someString.length)
x = "Hello"
# Hello World
print(f"{x} World")
const x = 'Hello'
// Hello World
console.log(`${x} World`)
x = """------
Line 1
Line 2
Line 3
------"""
# ------
# Line 1
# Line 2
# Line 3
# ------
print(x)
Multiline Stringsconst x = `------
Line 1
Line 2
Line 3
------`
// ------
// Line 1
// Line 2
// Line 3
// ------
console.log(x)
intstring_1 = "1"
number_1 = int(string_1)
# 3
print(number_1 + 2)
parseIntconst string1 = '1'
const number1 = parseInt(string1)
// 3
console.log(number1 + 2)
in# 2 is in the string
if "2" in "123":
print("2 is in the string")
# 2 is not in the string
if "2" not in "456":
print("2 is not in the string")
includes// 2 is in the string
if ('123'.includes('2')) {
console.log('2 is in the string')
}
// 2 is not in the string
if (!'456'.includes('2')) {
console.log('2 is not in the string')
}
[i:j]some_string = "0123456"
# 234
print(some_string[2:5])
substringconst someString = '0123456'
// 234
console.log(someString.substring(2, 5))
joinsome_list = ["a", "b", "c"]
# a,b,c
print(",".join(some_list))
joinconst someList = ['a', 'b', 'c']
// a,b,c
console.log(someList.join(','))
stripsome_string = " abc "
# abc
print(some_string.strip())
trimconst someString = ' abc '
// abc
console.log(someString.trim())
splitsome_string = "a,b,c"
some_string_split = some_string.split(",")
# a
print(some_string_split[0])
# b
print(some_string_split[1])
# c
print(some_string_split[2])
splitconst someString = 'a,b,c'
const someStringSplit = someString.split(',')
// a
console.log(someStringSplit[0])
// b
console.log(someStringSplit[1])
// c
console.log(someStringSplit[2])
replacesome_string = "a b c d e"
# a,b,c,d,e
print(some_string.replace(" ", ","))
Regular Expressions, replaceconst someString = 'a b c d e'
// Only changes the first space
// a,b c d e
// console.log(someString.replace(' ', ','))
// Use / /g instead of ' ' to change every space
console.log(someString.replace(/ /g, ','))
searchimport re
# Has a number
if re.search(r"\d", "iphone 8"):
print("Has a number")
# Doesn't have a number
if not re.search(r"\d", "iphone x"):
print("Doesn't have a number")
Regular Expressions, match// Has a number
if ('iphone 8'.match(/\d/g)) {
console.log('Has a number')
}
// Doesn't have a number
if (!'iphone x'.match(/\d/g)) {
console.log("Doesn't have a number")
}
some_list = [6, 3, 5]
# 6
# 3
# 5
for item in some_list:
print(item)
forEachconst someList = [6, 3, 5]
// 6
// 3
// 5
someList.forEach(element => {
console.log(element)
})
lensome_list = [1, 4, 9]
# 3
print(len(some_list))
lengthconst someList = [1, 4, 9]
// 3
console.log(someList.length)
in# 2 is in the list
if 2 in [1, 2, 3]:
print("2 is in the list")
# 2 is not in the list
if 2 not in [4, 5, 6]:
print("2 is not in the list")
includes// 2 is in the list
if ([1, 2, 3].includes(2)) {
console.log('2 is in the list')
}
// 2 is not in the list
if (![4, 5, 6].includes(2)) {
console.log('2 is not in the list')
}
reversed, listsome_list = [1, 2, 3, 4]
# reversed(some_list) is just an iterable.
# To convert an iterable into a list, use list()
reversed_list = list(reversed(some_list))
# 4
# 3
# 2
# 1
for item in reversed_list:
print(item)
# You can use an iterable instead of a list in a for loop
# for item in reversed(some_list):
reverseconst someList = [1, 2, 3, 4]
someList.reverse()
// 4
// 3
// 2
// 1
someList.forEach(element => {
console.log(element)
})
range# 0
# 1
# 2
# 3
for i in range(4):
print(i)
# 4
# 5
# 6
# 7
for i in range(4, 8):
print(i)
# 6
# 5
# 4
for i in range(6, 3, -1):
print(i)
// 0
// 1
// 2
// 3
for (let i = 0; i < 4; i++) {
console.log(i)
}
// 4
// 5
// 6
// 7
for (let i = 4; i < 8; i++) {
console.log(i)
}
// 6
// 5
// 4
for (let i = 6; i > 3; i--) {
console.log(i)
}
appendsome_list = [1, 2]
some_list.append(3)
# 1
# 2
# 3
for x in some_list:
print(x)
pushconst someList = [1, 2]
someList.push(3)
// 1
// 2
// 3
someList.forEach(element => {
console.log(element)
})
Unpackingoriginal_list = [1, 2]
# [original_list, 3] -> [[1, 2], 3]
# [*original_list, 3] -> [1, 2, 3]
new_list = [*original_list, 3]
original_list[0] = 5
# 1
# 2
# 3
for x in new_list:
print(x)
Spreadconst originalList = [1, 2]
// [originalList, 3] -> [[1, 2], 3]
// [...originalList, 3] -> [1, 2, 3]
const newList = [...originalList, 3]
originalList[0] = 5
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
extendsome_list = [1]
some_list.extend([2, 3])
# 1
# 2
# 3
for x in some_list:
print(x)
Spreadconst someList = [1]
someList.push(...[2, 3])
// 1
// 2
// 3
someList.forEach(element => {
console.log(element)
})
List additionoriginal_list = [1]
new_list = original_list + [2, 3]
original_list[0] = 5
# 1
# 2
# 3
for x in new_list:
print(x)
concatconst originalList = [1]
const newList = originalList.concat([2, 3])
originalList[0] = 5
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
insertsome_list = [4, 5]
some_list.insert(0, 3)
# 3
# 4
# 5
for x in some_list:
print(x)
unshiftconst someList = [4, 5]
someList.unshift(3)
// 3
// 4
// 5
someList.forEach(element => {
console.log(element)
})
delsome_list = ["a", "b", "c"]
del some_list[1]
# a
# c
for x in some_list:
print(x)
spliceconst someList = ['a', 'b', 'c']
someList.splice(1, 1)
// a
// c
someList.forEach(element => {
console.log(element)
})
popsome_list = [1, 2, 3, 4]
# 4
print(some_list.pop())
# 1
print(some_list.pop(0))
# 2
# 3
for x in some_list:
print(x)
indexsome_list = ["a", "b", "c", "d", "e"]
# 2
print(some_list.index("c"))
indexOfconst someList = ['a', 'b', 'c', 'd', 'e']
// 2
console.log(someList.indexOf('c'))
[i:j]original_list = [1, 2, 3]
new_list = original_list[:] # or original_list.copy()
original_list[2] = 4
# 1
# 2
# 3
for x in new_list:
print(x)
Spreadconst originalList = [1, 2, 3]
const newList = [...originalList]
originalList[2] = 4
// 1
// 2
// 3
newList.forEach(element => {
console.log(element)
})
List Comprehensionsoriginal_list = [1, 2, 3]
new_list = [x * 2 for x in original_list]
# 2
# 4
# 6
for x in new_list:
print(x)
mapconst originalList = [1, 2, 3]
// You can also do this:
// const newList = originalList.map(x => { return x * 2 })
const newList = originalList.map(x => x * 2)
// 2
// 4
// 6
newList.forEach(element => {
console.log(element)
})
List Comprehensionsfirst_list = [1, 3]
second_list = [3, 4]
combined_list = [[x + y for y in second_list] for x in first_list]
# 4
print(combined_list[0][0])
# 5
print(combined_list[0][1])
# 6
print(combined_list[1][0])
# 7
print(combined_list[1][1])
mapconst firstList = [1, 3]
const secondList = [3, 4]
const conbinedList = firstList.map(x => {
return secondList.map(y => {
return x + y
})
})
// 4
console.log(conbinedList[0][0])
// 5
console.log(conbinedList[0][1])
// 6
console.log(conbinedList[1][0])
// 7
console.log(conbinedList[1][1])
List Comprehensionsoriginal_list = [1, 2, 3, 4, 5, 6]
new_list = [x for x in original_list if x % 2 == 0]
# 2
# 4
# 6
for x in new_list:
print(x)
filterconst originalList = [1, 2, 3, 4, 5, 6]
const newList = originalList.filter(x => x % 2 == 0)
// 2
// 4
// 6
newList.forEach(element => {
console.log(element)
})
sumsome_list = [1, 2, 3]
# 6
print(sum(some_list))
reduceconst someList = [1, 2, 3]
const reducer = (accumulator, currentValue) => accumulator + currentValue
// 6
console.log(someList.reduce(reducer))
ziplist_1 = [1, 3, 5]
list_2 = [2, 4, 6]
# 1 2
# 3 4
# 5 6
for x, y in zip(list_1, list_2):
print(f"{x} {y}")
mapconst list1 = [1, 3, 5]
const list2 = [2, 4, 6]
// [[1, 2], [3, 4], [5, 6]]
const zippedList = list1.map((x, y) => {
return [x, list2[y]]
})
zippedList.forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
[i:j]original_list = ["a", "b", "c", "d", "e"]
new_list = original_list[1:3]
original_list[1] = "x"
# b
# c
for x in new_list:
print(x)
sliceconst originalList = ['a', 'b', 'c', 'd', 'e']
const newList = originalList.slice(1, 3)
originalList[1] = 'x'
// b
// c
newList.forEach(element => {
console.log(element)
})
sortedsome_list = [4, 2, 1, 3]
# 1
# 2
# 3
# 4
for item in sorted(some_list):
print(item)
sortconst someList = [4, 2, 1, 3]
// 1
// 2
// 3
// 4
someList.sort().forEach(element => {
console.log(element)
})
sortedsome_list = [["c", 2], ["b", 3], ["a", 1]]
# a 1
# c 2
# b 3
for item in sorted(some_list, key=lambda x: x[1]):
print(f"{item[0]} {item[1]}")
sortconst someList = [['c', 2], ['b', 3], ['a', 1]]
// a 1
// c 2
// b 3
someList
.sort((a, b) => {
return a[1] - b[1]
})
.forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
itemssome_dict = {"one": 1, "two": 2, "three": 3}
# one 1
# two 2
# three 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.items())
for key, value in some_dict.items():
print(f"{key} {value}")
entriesconst someDict = { one: 1, two: 2, three: 3 }
// one 1
// two 2
// three 3
Object.entries(someDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
insome_dict = {"one": 1, "two": 2, "three": 3}
# one is in the dict
if "one" in some_dict:
print("one is in the dict")
# four is not in the dict
if "four" not in some_dict:
print("four is not in the dict")
hasOwnPropertyconst someDict = { one: 1, two: 2, three: 3 }
// one is in the dict
if (someDict.hasOwnProperty('one')) {
console.log('one is in the dict')
}
// four is not in the dict
if (!someDict.hasOwnProperty('four')) {
console.log('four is not in the dict')
}
original_dict = {"one": 1, "two": 2}
original_dict["three"] = 3
# one 1
# two 2
# three 3
for key, value in original_dict.items():
print(f"{key} {value}")
const originalDict = { one: 1, two: 2 }
originalDict.three = 3
// one 1
// two 2
// three 3
Object.entries(originalDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
Unpackingoriginal_dict = {"one": 1, "two": 2}
new_dict = {**original_dict, "three": 3}
original_dict["one"] = 100
# one 1
# two 2
# three 3
for key, value in new_dict.items():
print(f"{key} {value}")
Spreadconst originalDict = { one: 1, two: 2 }
const newDict = { ...originalDict, three: 3 }
originalDict.one = 100
// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
keyssome_dict = {"one": 1, "two": 2, "three": 3}
# one
# two
# three
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.keys())
for x in some_dict.keys():
print(x)
keysconst someDict = { one: 1, two: 2, three: 3 }
// one
// two
// three
Object.keys(someDict).forEach(element => {
console.log(element)
})
valuessome_dict = {"one": 1, "two": 2, "three": 3}
# 1
# 2
# 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.values())
for x in some_dict.values():
print(x)
valuesconst someDict = { one: 1, two: 2, three: 3 }
// 1
// 2
// 3
Object.values(someDict).forEach(element => {
console.log(element)
})
delsome_dict = {"one": 1, "two": 2, "three": 3}
del some_dict["two"]
# one 1
# three 3
for key, value in some_dict.items():
print(f"{key} {value}")
deleteconst someDict = { one: 1, two: 2, three: 3 }
delete someDict.two
Object.entries(someDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
getsome_dict = {"one": 1, "two": 2, "three": 3}
# some_dict["four"] will be KeyError
# Doesn't exist
print(some_dict.get("five", "Doesn't exist"))
||const someDict = { one: 1, two: 2, three: 3 }
// Doesn't exist
console.log(someDict.five || "Doesn't exist")
Dictionary Comprehensionsoriginal_list = {"one": 1, "two": 2}
# {"one": 1, "two": 4}
new_list = {key: value * value for key, value in original_list.items()}
# one 1
# two 4
for key, value in new_list.items():
print(f"{key} {value}")
entriesconst originalDict = { one: 1, two: 2 }
const newDict = {}
Object.entries(originalDict).forEach(element => {
// newDict.element[0] doesn't work - for variable key use []
newDict[element[0]] = element[1] * element[1]
})
// one 1
// two 4
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
copyoriginal_dict = {"one": 1, "two": 2, "three": 3}
new_dict = original_dict.copy()
original_dict["one"] = 100
# one 1
# two 2
# three 3
for key, value in new_dict.items():
print(f"{key} {value}")
Spreadconst originalDict = { one: 1, two: 2, three: 3 }
const newDict = { ...originalDict }
originalDict.one = 100
// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
json.dumpsimport json
some_dict = {"one": 1, "two": 2, "three": 3}
# {
# "one": 1,
# "two": 2,
# "three": 3
# }
print(json.dumps(some_dict, indent=2))
JSON.stringifyconst someDict = { one: 1, two: 2, three: 3 }
// {
// "one": 1,
// "two": 2,
// "three": 3
// }
console.log(JSON.stringify(someDict, null, 2))
json.loadsimport json
some_json = """{
"one": 1,
"two": 2,
"three": 3
}"""
dict_from_json = json.loads(some_json)
# 2
print(dict_from_json["two"])
JSON.parseconst someJson = `{
"one": 1,
"two": 2,
"three": 3
}`
const dictFromJson = JSON.parse(someJson)
// 2
console.log(dictFromJson.two)
some_variable = 2
some_dict = {(some_variable + 1): "three"}
# three
print(some_dict[3])
Computed Property Namesconst someVariable = 2
const someDict = { [someVariable + 1]: 'three' }
// three
console.log(someDict[3])
def add(x, y):
print(f"Adding {x} and {y}")
return x + y
# Adding 1 and 2
# 3
print(add(1, 2))
const add = (x, y) => {
console.log(`Adding ${x} and ${y}`)
return x + y
}
// Adding 1 and 2
// 3
console.log(add(1, 2))
def add(a, b, c):
return a + b + c
# 6
print(add(b=1, a=2, c=3))
const add = ({ a, b, c }) => {
return a + b + c
}
// 6
console.log(
add({
b: 1,
a: 2,
c: 3
})
)
def greet(name, word="Hello"):
print(f"{word} {name}")
# Hello World
greet("World")
# Goodbye World
greet("World", "Goodbye")
Default Parametersconst greet = (name, word = 'Hello') => {
console.log(`${word} ${name}`)
}
// Hello World
greet('World')
// Goodbye World
greet('World', 'Goodbye')
def greet(name="World", word="Hello"):
print(f"{word} {name}")
# Goodbye World
greet(word="Goodbye")
# Hello Programming
greet(name="Programming")
Default Valueconst greet = ({ name = 'World', word = 'Hello' }) => {
console.log(`${word} ${name}`)
}
// Goodbye World
greet({ word: 'Goodbye' })
// Hello Programming
greet({ name: 'Programming' })
Arbitrary Argument Listsdef positional_args(a, b, *args):
print(a)
print(b)
for x in args:
print(x)
# 1
# 2
# 3
# 4
positional_args(1, 2, 3, 4)
Rest Parametersconst positionalArgs = (a, b, ...args) => {
console.log(a)
console.log(b)
args.forEach(element => {
console.log(element)
})
}
// 1
// 2
// 3
// 4
positionalArgs(1, 2, 3, 4)
Keyword Argumentsdef func_1(**kwargs):
for key, value in kwargs.items():
print(f"{key} {value}")
def func_2(x, *args, **kwargs):
print(x)
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key} {value}")
# one 1
# two 2
func_1(one=1, two=2)
# 1
# 2
# 3
# a 4
# b 5
func_2(1, 2, 3, a=4, b=5)
Rest Parametersconst func1 = kwargs => {
Object.entries(kwargs).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
}
// ...args must be the last argument
const func2 = (x, kwargs, ...args) => {
console.log(x)
args.forEach(element => {
console.log(element)
})
Object.entries(kwargs).forEach(element => {
console.log(`${element[0]} ${element[1]}`)
})
}
// one 1
// two 2
func1({ one: 1, two: 2 })
// 1
// 2
// 3
// a 4
// b 5
func2(1, { a: 4, b: 5 }, 2, 3)
Classesclass Duck:
def __init__(self, name):
self.name = name
def fly(self):
print(f"{self.name} can fly")
# not @classmethod: call a method on an instance
# duck = Duck(...)
# duck.create(...)
#
# @classmethod: call a method on a class
# Duck.create(...)
@classmethod
def create(cls, name, kind):
if kind == "mallard":
return MallardDuck(name)
elif kind == "rubber":
return RubberDuck(name)
else:
# cls = Duck
return cls(name)
class MallardDuck(Duck):
# @property:
# use duck.color instead of duck.color()
@property
def color(self):
return "green"
class RubberDuck(Duck):
def __init__(self, name, eye_color="black"):
super().__init__(name)
self.eye_color = eye_color
def fly(self):
super().fly()
print(f"Just kidding, {self.name} cannot fly")
@property
def color(self):
return "yellow"
regularDuck = Duck("reggie")
# reggie can fly
regularDuck.fly()
mallardDuck = Duck.create("mal", "mallard")
# mal
print(mallardDuck.name)
# green
print(mallardDuck.color)
rubberDuck = RubberDuck("vic", "blue")
# vic can fly
# Just kidding, vic cannot fly
rubberDuck.fly()
# yellow
print(rubberDuck.color)
# blue
print(rubberDuck.eye_color)
Classes, Method Definitions, static, get, superclass Duck {
constructor(name) {
this.name = name
}
fly() {
console.log(`${this.name} can fly`)
}
// not static: call a method on an instance
// const duck = new Duck(...)
// duck.create(...)
//
// static: call a method on a class
// Duck.create(...)
static create(name, kind) {
if (kind === 'mallard') {
return new MallardDuck(name)
} else if (kind === 'rubber') {
return new RubberDuck(name)
} else {
// this = Duck
return new this(name)
}
}
}
class MallardDuck extends Duck {
// get:
// use duck.color instead of duck.color()
get color() {
return 'green'
}
}
class RubberDuck extends Duck {
constructor(name, eyeColor = 'black') {
super(name)
this.eyeColor = eyeColor
}
fly() {
super.fly()
console.log(`Just kidding, ${this.name} cannot fly`)
}
get color() {
return 'yellow'
}
}
const regularDuck = new Duck('reggie')
// reggie can fly
regularDuck.fly()
const mallardDuck = Duck.create('mal', 'mallard')
// mal
console.log(mallardDuck.name)
// green
console.log(mallardDuck.color)
rubberDuck = new RubberDuck('vic', 'blue')
// vic can fly
// Just kidding, vic cannot fly
rubberDuck.fly()
// yellow
console.log(rubberDuck.color)
// blue
console.log(rubberDuck.eyeColor)