文章目錄
- a.x = a = { }, 深入理解賦值運算式
- if 語句的簡寫
- && 和 || 的計算取值
- Object的構造
- prototype中的一些細節
- 建立對象,並保持原型鏈
a.x = a = { }, 深入理解賦值運算式
代碼
var o = {x : 1};
var a = o;
a.x = a = {name:100};
console.log(a.x); // undefined
console.log(o.x); // {name:100}
// a.x = a = {name:100};
// 等價於 a.x = (a = {name:100});
// 首先計算a.x的引用,然後計算(a = {name:100})的傳回值
if 語句的簡寫
var condition = true, numb = 0;
if(condition) {
alert('rain-man')
}
if(condition) {
numb = 1 + 2;
}
等同於
var condition = true, numb = 0;
condition && alert('rain-man');
condition && (numb = 1 + 2);
&& 和 || 的計算取值
(true && 222); // 222
!!(true && 222); // true
(false && 222 ); // false
(false || 222); // 222
!!(false || 222); // true
!!variable 會返回和原值相等的boolean值
Object的構造
代碼
function Object() { [native code] }
Object.prototype = {
constructor: function Object() { [native code] },
hasOwnProperty: function hasOwnProperty() { [native code] },
isPrototypeOf: function isPrototypeOf() { [native code] },
propertyIsEnumerable: function propertyIsEnumerable() { [native code] },
toLocaleString: function toLocaleString() { [native code] },
toString: function toString() { [native code] },
valueOf: function valueOf() { [native code] }
};
Object.prototype.constructor === Object; // true
prototype中的一些細節
var A = function(){
this.name = 'rain-man';
};
A.prototype = {
name : 'cnblogs'
};
var o = new A();
console.log(o.name); // 'rain-man'
建立對象,並保持原型鏈
代碼
var O = function(obj) {
function T() {}
T.prototype = obj;
return new T();
};
var obj = {name: 'obj', age: 0 },
obj1 = O(obj),
obj2 = O(obj1);
// 更改原型鏈的一處,所有原型鏈都會更改
obj.name = 'superclass';
console.log(obj1.name); // 'superclass'
console.log(obj2.name); // 'superclass'
// 每一層可單獨處理
obj1.name = 100;
console.log(obj1.name); //100
delete obj1.name; //暴漏原型鏈
console.log(obj1.name); // 'superclass'