1、
在函数内使用this.name(变量名)的方式赋值,当函数作为普通函数调用时,在函数外部可以直接访问到,这是因为这里的this指向window:
function fn(){ var r = 2 ; this.ss = 0; this.sum=function(num1,num2){ return (num1+num2)*r; }; } fn(); //var b = new fn(); console.log(ss); //0 console.log(window.sum(1,2)); //6 console.log(sum(1,2)); //6
当函数作为方法函数调用时,情况又有所不同,这时候this指向发生变化,指向自身:
function fn(){ var r = 2 ; this.ss = 0; this.sum=function(num1,num2){ return (num1+num2)*r; }; } var b = new fn(); /* console.log(ss); //error 报错 console.log(window.sum(1,2)); //error 报错 console.log(sum(1,2)); //error 报错 */ //可以通过实例访问 console.log(b.ss); //0 console.log(b.sum(1,2)); //6
2、
var a ; function fn2(){ var b = 0; return b ; }; a = fn2(); console.log(a); //0
来源:https://www.cnblogs.com/xiaowan-/p/5595888.html