JavaScriptのいくつかのオブジェクトを作成する方法について
2763 ワード
// Nicholas C.Zakas《Professional JavaScript for Web Developers》
//
var person = new Object();
person.name = "Nicholas";
person.sayName = function() {
console.log(this.name);
};
//
var dog = {
name: "Tom",
age: 12,
sayName: function() {
console.log(this.name);
}
};//
//
function createPig(name, age, job) {
var o = new Object();
o.name = name;
o.age = 11;
o.job = job;
o.sayName = function() {console.log(this.name);};
return o;
};//
//
function Mouse(name, age, job) {
this.name = name;
this.age = 11;
this.job = job;
this.sayName = function() {console.log(this.name);};
};// ( )
// :
function Duck(){};
Duck.prototype.name = "Tang";
Duck.prototype.sayName = function() {console.log(this.name)};
var duck = new Duck();
/*
4 : 、 、
[[Configurable]]: delete
[[Enumerable]]: for-in
[[Writable]]:
[[Value]]
*/
function DataPropertyModify() {
var cat = {};
// : 、 、 [ : 4 ]
//configurable false
Object.defineProperty(cat, "name", {
configurable: false,
writable: false,
value: "John"
});
console.log(cat.name);
cat.name = "Greg";
console.log(cat.name);
};
/*
[[Configurable]]: delete
[[Enumerable]]: for-in
[[Get]]:
[[Set]]:
*/
function constructorPropertyModify() {
var computer = {};
var book = {
//
_year: 2004,
edition: 1
};
Object.defineProperty(book, "year", {
get: function() {
return this._year;
},// getter
set: function(newValue) {
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue -2004;
}
}
});
book.year = 2005;
console.log(book.edition);
Object.defineProperties(computer, {
_year: {value: 2004},
edition: {value: 1},
year: {
get: function(){return this._year},
set: function(newValue) {
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue -2004;
}
}
},
});
computer.year = 2006;
console.log(computer.edition);
};
function hasPrototypeProperty(object, name) {
return !object.hasOwnProperty(name) && (name in object);
}
domReady(function(){
//
var mouse = new Mouse("Tom", 2, "software");
mouse.sayName();
//
Mouse("Tom", 2, "software");
window.sayName();
//
var mo = new Object();
Mouse.call(mo, "Kristen", 25, "Nurse");
mo.sayName();
console.log(" ");
person.sayName();
DataPropertyModify();
constructorPropertyModify();
});