是否可以使用三种不同的语法来完成相同的结果?我已经做了前两个,但是需要对象文字的帮助
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 ????????????
所以对象文字语法看起来像这样。
Animal = {
noice: 'Moooo',
speak: function(){ return this.noice },
eat: function(){ return this }
}
var cow = Object.create(Animal)
cow.speak() // Moooo
[Object.create()使用现有对象(动物)作为新创建的对象的原型来创建新对象。
因此,新的cow
对象不具有其自身的属性,但是其原型将指向Animal对象。
没有办法仅使用对象文字语法在对象的原型中放置方法。但是您可以使其与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