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

问题描述 投票:1回答:2

是否可以使用三种不同的语法来完成相同的结果?我已经做了前两个,但是需要对象文字的帮助

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

Class:

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 ????????????
javascript
2个回答
1
投票

所以对象文字语法看起来像这样。

Animal = {
  noice: 'Moooo',
  speak: function(){ return this.noice },
  eat: function(){ return this }
}

var cow = Object.create(Animal)
cow.speak() // Moooo

[Object.create()使用现有对象(动物)作为新创建的对象的原型来创建新对象。

因此,新的cow对象不具有其自身的属性,但是其原型将指向Animal对象。


0
投票

没有办法仅使用对象文字语法在对象的原型中放置方法。但是您可以使其与Object.create和自定义构造函数一起使用:

"use strict"
function Animal() {
  return Object.create({
    speak: function() {
      return this
    }
  });
}

Animal.eat = function() {
  return this
} 

const animal = Animal();
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
© www.soinside.com 2019 - 2024. All rights reserved.