一、特性
- 封装
- 继承
- 多态
二、ES6类
- 在es6中类没有变量提升,所以必须先定义类,才能通过类实例化方法
- 类里面所有的公用属性和方法一定要加this使用
1、es6创建类用到了class关键字
class Star {
constructor(name,age){
this.name = name;
this.age = age;
}
sing(song) {
console.log(this.name+ song)
}
}
var ldh = new Star('刘德华', 18);
var zxy = new Star('张学友', 16);
console.log(ldh.age);
console.log(zxy.age);
ldh.sing('冰雨');
zxy.sing('李香兰');
2、es6类里面继承使用关键字extends
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
money() {
console.log(100);
}
sum() {
console.log(this.x + this.y)
}
}
class Son extends Father {
constructor(x, y) {
super(x, y);
this.x = x;
this.y = y
}
sum() {
super.sum()
}
}
var son = new Son(1, 2);
son.money();
son.sum();
3、ES5中创建构造函数和原型
1、创建语法
function Star(name,age) {
this.name = name;
this.age = age;
this.sing = function(){
console.log(this.name+ song)
}
}
var ldh = new Star('刘德华',18)
ldh.sing()
Star.sex = '男';
console.log(Star.sex);
2、构造函数原型prototype
- 1、 构造函数存在浪费内存问题,所以需要共享就会用到prototype
- 2、javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象,这个prototype本身也是一个对象。这个对象所有的属性和方法都会被构造函数所有
Star().prototype.dace= function() {
console.log(100)
}
ldh.dace()
3.对象原型 __proto__
console.log(ldh.__proto__ == Star.prototype)
4、constructor属性
- 1、对象原型
__proto__
和原型对象prototype都有一个属性constructor,指回构造函数本身 - 2、很多情况下,我们需要手动利用constructor这个属性,指回原来的构造函数
function Star1() {
}
Star1().prototype.sing = function() {
}
Star1().prototype.song = function() {
}
Star1().prototype = {
constructor:Star1,
sing:function() {
}
}
5、ES5继承
function Father1(username,ages){
this.username = username;
this.ages = ages;
}
Father1.prototype.exam ={
}
Son2.prototype = new Father1();
Son2.prototype.constructor = Son;
function Son2(username,ages){
Father1.call(this,username,ages);
}
var son = new Son('lm','20');
console.log(son);
var o = {
name:'12'
}
function fn(){
}
var f = fn.bind(o);
console.log(f())
三、闭包和递归
var car = (function(){
var start = 13;
var total = 0
return {
price:function(){
return total;
},
yd:function(flag){
return flag;
}
}
})
car.price();
car.yd();
function fn1(){
fn1();
}
fn1();
Object.assign()
var obj = {
sh:{
}
}
for (i in obj){
}
function deepCopy(newobj,oldobj){
for (let k in oldobj) {
let item = oldobj[k];
if(item instanceof Array){
newobj[k] = [];
deepCopy(newobj[k],item);
}else if(item instanceof Object){
newobj[k] = {};
deepCopy(newobj[k],item);
}else{
newobj[k] = item;
}
}
}
var a = 12
var str = `${a} 仲夏夜之梦`
console.log(str);