let a=12,b=5;
let json = {
a,
b
}
console.log(json) // { a:12 , b:5 }
let persen ={
name:'倩倩',
age:18,
showName(){
alert(this.name)
}
}
persen.showName()
传统面向对象:类和构造函数在一起,为对象添加方法时使用prototype。传统面向对象实例如下:
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.showName = function(){
console.log('我叫',this.name)
}
Person.prototype.showAge = function(){
console.log('今年',this.age,'岁')
}
var p = new Person('倩倩',18)
p.showName()
p.showAge()
ES6面向对象:将类和构造函数分开。
类:class
构造函数:constructor指生成完实例之后,自己就执行的函数。
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
//给对象添加方法
showName(){
console.log('我叫',this.name)
}
showAge(){
console.log('今年',this.age,"岁")
}
}
var p =new Person('倩倩',18);
p.showName();
p.showAge()
传统面向对象的继承:
传统面向对象的继承实例如下:
function Person(name,age){
this.name = name;
this.age = age
}
Person.prototype.showName = function(){
console.log('我叫',this.name)
}
Person.prototype.showAge = function(){
console.log('今年',this.age,'岁')
}
function Worker(name,age,job){
Person.apply(this,arguments)//继承属性
this.job = job
}
Worker.prototype = new Person();//继承方法
Worker.prototype.showJob = function(){
console.log('工作是',this.job);
}
var w = new Worker('倩倩',18,'打杂');
w.showName();
w.showAge();
w.showJob();
ES6面向对象继承:
使用extends实现子类对父级的继承,super()将父类的属性继承过来。
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
showName(){
console.log('我叫',this.name)
}
showAge(){
console.log('今年',this.age,"岁")
}
}
class Worker extends Person {
constructor(name,age,job){
super(name,age)
this.job = job
}
showJob(){
console.log('工作是',this.job)
}
}
var w = new Worker('倩倩',18,'打杂');
w.showName();
w.showAge();
w.showJob()
关于super:
子类中有constructor,内部就要有super,因为子类没有自己的this对象,需要继承父类的this对象。
这里的super(name,age)就是调用父类的构造函数。
super 虽然代表了Person的构造函数,但是返回的是子类Worker的实例。
页面更新:2024-04-29
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号