前言:記錄對對象屬性
的再次學(xué)習(xí),對象屬性
很多概念性都比較容易讓人混淆(至少我是經(jīng)常的混淆... 大笑ing - )
1. hasOwnProperty和in屬性
hasOwnProperty的作用:檢查對象中是否存在指定的實(shí)例屬性,重點(diǎn)是
實(shí)例
而非原型
屬性。hasOwnProperty個人直譯:擁有自己的屬性...方便好記??
語法:對象.hasOwnProperty(“屬性名”)
代碼示例
<script>
//01 提供一個構(gòu)造函數(shù)
function User(name) {
this.name = name;
}
//02 設(shè)置構(gòu)造函數(shù)的原型對象的屬性
User.prototype.todo = function () {
console.log("to do some...");
}
User.prototype.des = "默認(rèn)的描述信息";
//03 創(chuàng)建對象
var user = new User();
//04 使用hasOwnProperty方法判斷該屬性是否是對象的實(shí)例屬性
console.log(user.hasOwnProperty("age")); //false
console.log(user.hasOwnProperty("name")); //true
console.log(user.hasOwnProperty("todo")); //false
console.log(user.hasOwnProperty("des")); //false
</script>
in關(guān)鍵字作用:用來檢查對象中是否存在某個屬性(不區(qū)分實(shí)例屬性和原型屬性)...??如果是用在for循環(huán)上的in就不是這個意思了
語法:“屬性名” in 對象
代碼示例
<script>
//01 提供一個構(gòu)造函數(shù)
function User(name) {
this.name = name;
}
//02 設(shè)置構(gòu)造函數(shù)的原型對象的屬性
User.prototype.todo = function () {
console.log("to do some...");
}
//03 創(chuàng)建對象
var user = new User();
//04 使用in關(guān)鍵字判斷對象中是否存在以下屬性:name age todo
console.log("age" in user); //false
console.log("name" in user); //true
console.log("todo" in user); //true
</script>
那么我們?nèi)绾闻袛鄬ο笾兄淮嬖?code>原型屬性呢?
function isProperty(obj, property) {
return !obj.hasOwnProperty(property) && (property in obj);
}
如果想知道
user
是屬于某個構(gòu)造函數(shù)時直接user.constructor
查看如果想要判斷
user
這個對象是不是User
構(gòu)造函數(shù)的實(shí)例時用instanceof
檢查
console.log(user instanceof User); //true
console.log(user instanceof Object); //true
//instanceof 直接查到整條原型鏈
- 如果還要判斷
User
是不是user
的原型對象時,可以用isPrototypeOf
console.log(User.prototype.isPrototypeOf(user)); //rue
總結(jié):會很容易懵逼... 前方的道路還是很多霧霾...且行且懵逼...