对象下

108 阅读1分钟

构造函数内部原理//有new后函数里面发生方法执行,那么会发生隐式,没new正常执行

1.在函数最前面隐式的加上 var this = {}
2.执行this...=...;
3.隐式的返回this

this是JavaScript语言的一个关键字。 它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。 随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。

// 例子

<script type="text/javascript">
function Person(name,height){
    // var this={}
    this.name = name;
    this.height = height;
    this.say = function(){
        console.log(this.say);
    }
    // 隐式的return this
}
//var people = new Person('xiaowang',180)         //方法一
//console.log(new Person('xiaowang',180).name);   //方法二
// new Person返回对象,这里不拿变量接收,直接用
</script>

显式的return例子

function Person(name,height){
    // var this={}
    this.name = name;
    this.height = height;
    this.say = function(){
        console.log(this.say);
    }
    // 如果显式的返回return 那么隐式没用
    // return {};//例1
    //return 123;//例2--系统回归正常状态,必须返回对象值如数组、对象、function等,所以不能返回原始值,直接返回对象图2
}
var person = new Person('xiaowang',180);
var person1 = new Person('xiaoyang',175);

显示return例1.jpg

显示return例2.jpg

例子-模拟系统构造函数的方法,把隐式的步骤写出来,不用new---(这个方法不用,仅做扩展)

function Person(name,height){
    var that = {};
    that.name = name;
    that.height = height;
    return that;----------
}
var person = Person('xiaohu',170);
var person1 = Person('xiaoxiong',150);