我们创建构造函数的时候,原型对象上会有一个constructor属性,它是原型对象所独有的
1.instanceof
2.constructor
function Person(name,age){this.name = name;this.age = age;}var p = new Person("cheng",20);console.log(p.constructor==Person)var arr = [1,2,3];console.log(arr.constructor == Array)
1.改变原型对象
问题:就是我们以直接量(对象)形式,给原型对象添加属性的时候,它的
constructor会指向Object
需要:重置constructor
function Person(name,age){this.name = name;this.age = age;}/* 以字面量(对象)的形式给原型对象添加属性 */Person.prototype = {sayName:function(){console.log(this.name)},sayAge(){console.log(this.age)}}/* 问题:就是我们以直接量(对象)形式,给原型对象添加属性的时候,它的constructor会指向Object*/var p = new Person("cheng",20);console.log(p.constructor)console.log(p.constructor==Person) //重置constructorconsole.log(p instanceof Person)
2.公有属性和私有属性
在构造函数中
公有 在一般在原型对象上
私有属性 通过this关键字去添加的
hasOwnProperty可以判断属性是私有的还是共有的
Person.prototype = {constructor:Person,sayName:function(){console.log(this.name)},sayAge(){console.log(this.age)}}var p = new Person("cheng",20);console.log(p.hasOwnProperty("name"))console.log(p.hasOwnProperty("sayName"))
3.如何改变this关键字的指向call,apply,bind
函数正常调用的时候this指向window
函数要有对象去调用,事件也是需要对象去执行的
var name = "张三"function show(){console.log(this.name)}function go(){var name = "李四"show();}window.go();
call 可以改变函数内部this关键字的指向 funName.call(obj)
applay funName.applay(obj)
var name = "王五";var obj = {name:"李四"}function go(){console.log(this.name)}go();go.call(obj);go.apply(obj);
4.call,apply之间的区别
应用场景:传递多个参数的情况<br /> call 依次去传递<br /> applay 需要传递数组
var name = "window"var zhang = {name: "张三"}function show(a, b) {console.log(this.name);console.log(a + b)}// show(1,2)// show.call(zhang,2,3);show.apply(zhang,[1,2])
5.bind
bind绑定的函数不会马上执行,只是改变了函数上下文的执行环境
var name = "window"var zhang = {name: "张三"}var show = function(a,b){console.log(this.name)console.log(a+b);}.bind(zhang);show(2,3);
使用场景
<button id="btn">按钮</button><script>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){// console.log(this.id)window.setTimeout(function(){console.log(this.id)},1000)}
<button id="btn">按钮</button><script>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(function(){console.log(this.id)}.bind(btn),1000)}<script>
<button id="btn">按钮</button><script>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){var self = this;setTimeout(function(){console.log(this.id)}.bind(self),1000)}</script>
<button id="btn">按钮</button><script>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(function(){console.log(this.id)}.bind(this),1000)}</script>
可以使用箭头函数解决this指向的问题
var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(()=>{console.log(this.id)},1000)}
