每一个对象都会在其内部初始化一个属性,就是prototype(原型),当咱们访问一个对象的属性时,javascript
若是这个对象内部不存在这个属性,那么他就会去prototype里找这个属性,这个prototype又会有本身的prototype,因而就这样一直找下去,也就是咱们平时所说的原型链的概念。html
关系:instance.constructor.prototype = instance.__proto__java
原型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建立对象简单的说,无非就是使用内置对象或各类自定义对象,固然还能够用JSON;但写法有不少种,也能混合使用。
一、对象字面量的方式
person={firstname:"Mark",lastname:"Yun",age:25,eyecolor:"black"};
二、用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();
三、用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方法
四、用工厂方式来建立(内置对象)
var wcDog =new Object();
wcDog.name="旺财";
wcDog.age=3;
wcDog.work=function(){
alert("我是"+wcDog.name+",汪汪汪......");
}
wcDog.work();
五、用原型方式来建立
function Dog(){
}
Dog.prototype.name="旺财";
Dog.prototype.eat=function(){
alert(this.name+"是个吃货");
}
var wangcai =new Dog();
wangcai.eat();
五、用混合方式来建立
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(); 复制代码
null 表示一个对象被定义了,值为“空值”;
undefined 表示不存在这个值。
typeof undefined
//"undefined"
undefined :是一个表示"无"的原始值或者说表示"缺乏值",就是此处应该有一个值,可是尚未定义。当尝试读取时会返回 undefined;
例如变量被声明了,但没有赋值时,就等于undefined
typeof null
//"object"
null : 是一个对象(空对象, 没有任何属性和方法);
例如做为函数的参数,表示该函数的参数不是对象;
注意:
在验证null时,必定要使用 === ,由于 == 没法分别 null 和 undefined复制代码