javascript - 面试题两则,求指教。。
本文介绍了javascript - 面试题两则,求指教。。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
// ES5
var randy = new Person('Randy', 1995)
console.log(randy) // => {name: "Randy", birth: 1995}
randy.say('Hello') // => 'Randy: Hello'
// es6
var randy = new Person('Randy', 1995)
console.log(randy) // => {name: "Randy", birth: 1995}
randy.say('Hello') // => 'Randy: Hello'
console.log(randy.age) // => 22
randy.birth = 1998
console.log(randy.age) // => 19
分别用es5跟es6实现上面两个类
解决方案
// ES5
function Person(name,birth) {
this.name = name;
this.birth = birth;
}
Person.prototype.say = function (str) {
console.log(this.name+':'+str);
}
var randy = new Person('Randy', 1995)
console.log(randy);
randy.say('Hello');
//ES6
class Person{
constructor(name,birth,age){
this.name = name;
this.birth = birth;
}
get age(){
return new Date().getFullYear() - Number(this.birth);
}
say(str){
console.log(this.name+':'+str);
}
}
var randy = new Person('Randy', 1995)
console.log(randy);
randy.say('Hello');
console.log(randy.age);
randy.birth = 1998;
console.log(randy.age);
推荐看看这个ES6 Class
这篇关于javascript - 面试题两则,求指教。。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文