1.继承:原型链
function a(){
this.yy=[1,2]
}
a.prototype.say_a=function(){
console.log(this.yy)
}
function b(){
a.call(this)//继承属性
this.yyy=[3,4]
}
b.prototype=new a();//继承方法
b.prototype.say_b=function(){
console.log(this.yyy)
}
var c = new b();
var d = new b();
c.yy.push([3]);
c.yyy.push([5]);
c.say_a();//[ 1, 2, [ 3 ] ]
c.say_b();//[ 3, 4, [ 5 ] ]
console.log(c.yy)//[ 1, 2, [ 3 ] ]
console.log(c.yyy)//[ 3, 4, [ 5 ] ]
d.say_a();//[ 1, 2 ]
d.say_b();//[ 3, 4 ]
console.log(d.yy)//[ 1, 2 ]
console.log(d.yyy)//[ 3, 4 ]
console.log(a.prototype.yy)//undefined
console.log(a.yy)//undefined
console.log(b.prototype.yy)//[ 1, 2 ]
console.log(b.yy)//undefined
2.this
JavaScript 的 this 原理 - 阮一峰的网络日志 http://www.ruanyifeng.com/blog/2018/06/javascript-this.html
var f = function () {
console.log(this.x);
}
var x = 1;
var obj = {
f: f,
x: 2,
};
// 单独执行
f() // 1
// obj 环境执行
obj.f() // 2
this
指的是函数运行时所在的环境。对于obj.foo()
来说,foo
运行在obj
环境,所以this
指向obj
;对于foo()
来说,foo
运行在全局环境,所以this
指向全局环境。所以,两者的运行结果不一样。
var a=11
function test1(){
this.a=22;
let b=function(){
console.log(this.a);
};
b();//11
this.c=function(){
console.log(this.a);
};
// c();//报错,c is not defined
}
var x=new test1();
console.log(x.b);//undefined
//x.b()//报错, x.b is not a function
console.log(x.c);//[Function]
x.c();//22