javascript - 如何使用 Class、传统的基于函数和对象文字语法获得相同的结果?

标签 javascript

是否可以使用三种不同的语法实现相同的结果? 我已经完成了前两个,但需要有关对象字面量的帮助

  • 类语法
  • 传统的基于函数的语法
  • 对象文字语法 <<<---- 缺少 ??????

类:

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/

相关文章:

javascript - getDownloadURL 无法正常工作 - Firebase 存储 (Web)

javascript - 为什么 CSV 文件中的日期输出为 NaN?

javascript - 带有谷歌地图和 Ionic 3 的空白页

javascript - 我可以在 Web Worker 中使用模块吗?

javascript - infdig 无限 $digest 循环

javascript - 在 Vanilla JS 中触发 CustomEvent

JavaScript ECMAScript 6 - 错误 : "You can only use decorators on an export when exporting a class"

javascript - 在脚本中调整图像大小

javascript - 如何通过 Angular 在 JSON 文件中使用 HTML 标签/属性

javascript - 如何查看从给定文件开始的完整 Node "require()"树?