js的require、new、this机制

require:

1:js里面代码可以放在不同的文件里,称为代码模块;

2:一个模块需要引用其它模块代码的时候使用 require;

3: require:

         (1) 如果是第一次调用,那么就加载,执行脚本;    

         (2)  每个代码模块由module.exports 导出的对象;    

         (3) 每次require的时候,都返回module.exports;    

        (4)如果不是第一次执行,那么直接返回module.exports;

new 与构造函数:


// ===================new 与构造函数 机制=========================
function person(name, age) {
	this.name = name;
	this.age = age;
}
// 机制1 每一个函数对象都有一个表, prototype;
console.log(person.prototype);
person.prototype.get_age = function() {
	return this.age;
}

// 机制2: new 关键字 + 函数(参数)
// step1: 创建了一个新的表 {};
// step2: 调用person函数,并把这个新的表作为this传递给函数,进入person里面以后;
// person函数里面this 就是新建的表;
// step3: 将person构造函数的prototype这个表赋值给新的表(this)的.__proto__
// step4: 返回这个新的表;
// new 函数(参数) 的作用是构建一张新的表, 这个函数作为构造函数的作用是初始化表对象;
var blake = new person("Blake", 34);
console.log(blake);
var tom = new person("tom", 34);
console.log(tom);
var xiaoming = new person("xiaoming", 12);
console.log(xiaoming);
console.log(xiaoming.__proto__); // __proto__: get_age--> 函数对象;
// end

// 进入函数的时候,如果没有强制绑定this,就会根据隐士的调用规则,把xiaoming---> this
var ret = xiaoming.get_age()
ret = blake.get_age();
console.log(ret);

this机制:(bind、call)

function my_func(lhs, rhs) {
	console.log(this); // 使用this;
	console.log(lhs, rhs)
}

my_func(3 ,4); // 函数调用,隐式传递this,this可能是一个不确定的值;
// 函数.call: 显示的传递this
my_func.call({name: "aaa"}, 3, 4);

// 表.key 来隐式的传递this;
var tools = {
	my_func: my_func,
}
tools.my_func(3 ,4); // 表.函数key() --> this就是该表

//强制绑定this,
var new_func = my_func.bind({name:"bbb"});
new_func(5,6)

/**var bindedFun=fun.bind(obj)返回的函数固定了fun的this对象,通过bindedFun可以调用fun但是传递给fun的this是bind时候设置好的,固定不变的
**/
tools.my_func = new_func;
tools.my_func(3, 4);// 由上面的bind实现可知:此时this是{name: "bbb"}而不是tools。  

my_func(3, 4) // this是一个强制绑定的表, 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值