- 一切皆对象
- 对象是由函数创建的
原生构造函数:Array,String,Boolean,Number,RegExp,Function
let test = new Function("name","age","console.log(name,age)");
test('zzz',19);//zzz,19
- 一个函数能充当两个作用,函数也是对象(能调用),也能new,同时函数含有构造函数的功能(类函数)
function User(){}
let user = new User();
User.prototype.name='zzx'
class举例
class User2 {
constructor(name, age) {
this.name = name;
this.age = age;
}
/**
* 静态方法,可直接调用
*/
static drink() {
console.log("drinking")
}
/**
* 动态方法,必须new实例调用,挂在prototype上
*/
eat() {
console.log("eating")
}
}
let user = new User2('lucy','23');
user.eat();
User2.drink();
Arrray举例
// Arrray
let arr= [1,2,3,4]
console.log(arr.__proto__===Array.prototype) //true
//同理举例
let obj = {}
obj.__proto__===Object.prototype //true
// 函数举例
function Fun(name,age){
this.name=name;
this.age=age;
this.sayHi = function(){
console.log(name,age)
};
}
let child = new Fun('lisa',18);
child.__proto__===Fun.prototype //true
//加方法,通过prototype连接新方法,暴露给子用
Fun.prototype.sayHello=function () {
console.log(this.name,this.age,'sayHello')
}
console.dir(Fun) //
child.sayHi() //zzz 18
child.sayHello() //zzz 18 sayHello
Fun.__proto__.sayGoodMorning=function () {
console.log(this.name,this.age,'sayGoodMorning')
}
child.sayGoodMorning(); // Error:child.sayGoodMorning is not a function
//正确调用方法
Fun.__proto__.sayGoodMorning.call(child); //zzz 18 sayGoodMorning