是否可以使用三种不同的语法实现相同的结果? 我已经完成了前两个,但需要有关对象字面量的帮助
- 类语法
- 传统的基于函数的语法
- 对象文字语法 <<<---- 缺少 ??????
类:
class Animal {
speak() { return this }
static eat() { return this }
}
let obj = new Animal()
console.log(obj.speak()) // Animal {}
let speak = obj.speak
console.log(speak()) // undefined
console.log(Animal.eat()) // Animal
let eat = Animal.eat
console.log(eat()); // undefined
传统的基于函数的
"use strict"
function Animal() {}
Animal.prototype.speak = function() {return this}
Animal.eat = function() {return this}
let obj = new Animal();
console.log(obj.speak()); // Animal {}
let speak = obj.speak;
console.log(speak()); // undefined
console.log(Animal.eat()) // Animal
let eat = Animal.eat;
console.log(eat()); // undefined
对象字面量
"use strict"
Animal = {
speak: function(){ return this},
eat: function(){ return this }() // ????????????????
}
console.log(Animal.speak()) // Animal {}
let speak = Animal.speak;
console.log(speak()) // undefined
console.log(Animal.eat) // Animal ????????????????
let eat = Animal.eat;
console.log(eat()) // undefined ????????????
最佳答案
所以对象字面量语法看起来像这样。
Animal = {
noice: 'Moooo',
speak: function(){ return this.noice },
eat: function(){ return this }
}
var cow = Object.create(Animal)
cow.speak() // Moooo
Object.create()创建一个新的对象,使用一个已经存在的对象(Animal)作为新创建对象的原型(prototype)。
所以新的 cow
对象本身没有任何属性,但它的原型(prototype)将指向 Animal 对象。
关于javascript - 如何使用 Class、传统的基于函数和对象文字语法获得相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824603/