每一個對象都會在其內部初始化一個屬性,就是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複製代碼