es5 中类的2种基本实现方法

时间:2023-02-07 14:53:31

function test(){
this.a = 1;
this.func = function(){
// var a = 3;下面的this 取的是上面的1,这个不影响
return this.a + 2;
}
}

test.prototype.say = function(){
console.log('hello,world.')
}

var t = new test();
t.say()
console.log(typeof test)//function
console.log(typeof t)//object
console.log(t.a)
console.log(t.func())

function test1(){
this.a = 1000;
return this;
}

console.log(new test1().a)//1000
console.log(test1().a)//1000 这种只有return this 才行

//===================================

var obj = {
a : 1,
func:function(){
return this.a + 2;
}
}
var c = Object.create(obj)
console.log(obj.a)
console.log(obj.func())
console.log(c.func())//这种感觉多次一举

一种是通过函数,一种是object.涉及到javascript 的基础作用域,原型链,闭包.