// Constructor for MyClass
function MyClass(name){
// Create the new object with Object.create and using the
// prototype of MyClass as a base, and add a new read only
// property "name".
return Object.create(
MyClass.prototype,
{
name : {
//enumerable: false,
//writable : false,
value : name
}
}
)
}
// Dedine new properties on the prototype,
// using Object.defineProperties that allows
// more control over the properties.
Object.defineProperties(
MyClass.prototype,
{
test: // name of property
{
value: // value of property, in this case a function
function(){
console.log(this.name);
return this; // Return "this" to allow chaining
}
// No other attributes defined, and therefore using
// default values: read only, not enumerabe and
// not configurable.
},
setCord:
{
value:
function (x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
return this;
}
},
width:
{
get: // A getter
function() {
return this.x2 - this.x1;
},
set: // A setter
function(value) {
this.x2 = this.x1 + value;
}
},
height:
{
get:
function() {
return this.y2 - this.y1;
},
set:
function (value) {
this.y2 = this.y1 + value;
}
}
}
);
var a= MyClass('DEMO').test();
a.setCord(10,20,50,60); // Set the cords.
// Display the cords, and using the getters of with an height
// that calculates the with and height on the fly.
console.log(
"x1:%d, y1:%s, x2:%d, y2:%d, width:%d, height:%d",
a.x1, a.y1, a.x2, a.y2, a.width, a.height
);
a.width = 100; // Using the setter to set the new width.
a.height = 100;
// Show the new coordinates. Notice that x2, y2, widtgh
// and height has changed.
console.log(
"x1:%d, y1:%s, x2:%d, y2:%d, width:%d, height:%d",
a.x1, a.y1, a.x2, a.y2, a.width, a.height
);
Конечно, это возможно, конструкторы являются функциями. Но поведение конструктора, называемого как функция, отличается от того, что он называет его конструктором. – RobG
Если вы хотите называть его «MyClass (« demo2 »). Test()', то там * требуется *, чтобы быть экземпляром для вызова 'test' * on *. Если вы просто не хотите присваивать экземпляр переменной ... ну, новый MyClass ('demo2'). Test() 'отлично работает. – deceze