js原型
js每声明一个function,都有prototype原型,prototype原型是函数的一个默认属性,在函数的创建过程中由js编译器自动添加。
也就是说:当生产一个function对象的时候,就有一个原型prototype。
每个对象都会在其内部初始化一个属性,就是prototype(原型),当我们访问一个对象的属性时,
如果这个对象内部不存在这个属性,那么他就会去prototype里找这个属性,这个prototype又会有自己的prototype,于是就这样一直找下去,也就是我们平时所说的原型链的概念。
关系:instance.constructor.prototype = instance.__proto__
Javascript如何实现继承?
原型prototype机制或apply和call方法去实现较简单,建议使用构造函数与原型混合方式。 function Parent(){ this.name = 'wang'; } function Child(){ this.age = 28; } Child.prototype = new Parent();//继承了Parent,通过原型 var demo = new Child(); alert(demo.age); alert(demo.name);//得到被继承的属性 }复制代码
JavaScript继承的几种实现方式?
- 参考:,;
javascript创建对象的几种方式?
javascript创建对象简单的说,无非就是使用内置对象或各种自定义对象,当然还可以用JSON;但写法有很多种,也能混合使用。1、对象字面量的方式 person={firstname:"Mark",lastname:"Yun",age:25,eyecolor:"black"};2、用function来模拟无参的构造函数 function Person(){} var person=new Person();//定义一个function,如果使用new"实例化",该function可以看作是一个Class person.name="Mark"; person.age="25"; person.work=function(){ alert(person.name+" hello..."); } person.work();3、用function来模拟参构造函数来实现(用this关键字定义构造的上下文属性) function Pet(name,age,hobby){ this.name=name;//this作用域:当前对象 this.age=age; this.hobby=hobby; this.eat=function(){ alert("我叫"+this.name+",我喜欢"+this.hobby+",是个程序员"); } } var maidou =new Pet("麦兜",25,"coding");//实例化、创建对象 maidou.eat();//调用eat方法4、用工厂方式来创建(内置对象) var wcDog =new Object(); wcDog.name="旺财"; wcDog.age=3; wcDog.work=function(){ alert("我是"+wcDog.name+",汪汪汪......"); } wcDog.work();5、用原型方式来创建 function Dog(){ } Dog.prototype.name="旺财"; Dog.prototype.eat=function(){ alert(this.name+"是个吃货"); } var wangcai =new Dog(); wangcai.eat();5、用混合方式来创建 function Car(name,price){ this.name=name; this.price=price; } Car.prototype.sell=function(){ alert("我是"+this.name+",我现在卖"+this.price+"万元"); } var camry =new Car("凯美瑞",27); camry.sell(); 复制代码
This对象的理解。
- this总是指向函数的直接调用者(而非间接调用者);
- 如果有new关键字,this指向new出来的那个对象;
- 在事件中,this指向触发这个事件的对象,特殊的是,IE中的attachEvent中的this总是指向全局对象Window;
null,undefined 的区别?
null 表示一个对象被定义了,值为“空值”;undefined 表示不存在这个值。typeof undefined //"undefined" undefined :是一个表示"无"的原始值或者说表示"缺少值",就是此处应该有一个值,但是还没有定义。当尝试读取时会返回 undefined; 例如变量被声明了,但没有赋值时,就等于undefinedtypeof null //"object" null : 是一个对象(空对象, 没有任何属性和方法); 例如作为函数的参数,表示该函数的参数不是对象;注意: 在验证null时,一定要使用 === ,因为 == 无法分别 null 和 undefined复制代码