javascript - 面试题两则,求指教。。
阿神
阿神 2017-04-11 12:40:19
[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实现上面两个类

阿神
阿神

闭关修行中......

全部回复(2)
高洛峰
// 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

ringa_lee
function Person(name,birth){
  this.name = name;
  this.birth = birth;
}
Person.prototype = {
  constructor:Person,
  say:function(str) {
     return this.name + ': ' + str;
  },
  get age(){
    return new Date().getFullYear() - this.birth;
  }
  
}
class Person
{
  constructor(name,birth){
    this.name = name;
    this.birth = birth;
  }
  say(str) {return this.name + ": " +str;}
  get age() {return new Date().getFullYear()-this.birth}
  
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号