我想知道创建具有属性和方法的JavaScript对象的最佳方法是什么。
我见过有人用var self = this然后用self的例子。在所有函数中确保作用域总是正确的。
然后我看到了使用.prototype来添加属性的例子,而其他人则是内联的。
谁能给我一个适当的例子,一个JavaScript对象的一些属性和方法?
我想知道创建具有属性和方法的JavaScript对象的最佳方法是什么。
我见过有人用var self = this然后用self的例子。在所有函数中确保作用域总是正确的。
然后我看到了使用.prototype来添加属性的例子,而其他人则是内联的。
谁能给我一个适当的例子,一个JavaScript对象的一些属性和方法?
当前回答
继续鲍恩斯的回答
在es6中,你现在可以创建一个类
现在你可以这样做:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
所以延伸到一个圆(就像在另一个答案中一样)你可以这样做:
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
最终在es6中更干净,更容易阅读。
下面是一个很好的例子:
类形状{ 构造函数(x, y) { 这一点。X = X; 这一点。Y = Y; } toString () { 返回' Shape at ${this。x} $ {this.y} '; } } 类Circle扩展形状{ 构造函数(x, y, r) { 超级(x, y); 这一点。R = R; } toString () { let shapeString = super.toString(); 返回半径为${this.r}的圆形${shapeString}; } } let c = new Circle(1,2,4); Console.log (" + c, c);
其他回答
当一个人在构造函数调用期间使用关闭“this”的技巧时,是为了编写一个函数,可以被其他不希望调用对象上的方法的对象用作回调。这与“使范围正确”无关。
这是一个普通的JavaScript对象:
function MyThing(aParam) {
var myPrivateVariable = "squizzitch";
this.someProperty = aParam;
this.useMeAsACallback = function() {
console.log("Look, I have access to " + myPrivateVariable + "!");
}
}
// Every MyThing will get this method for free:
MyThing.prototype.someMethod = function() {
console.log(this.someProperty);
};
阅读Douglas Crockford关于JavaScript的文章,您可能会学到很多东西。约翰·瑞西格也很出色。好运!
var Person = function (lastname, age, job){
this.name = name;
this.age = age;
this.job = job;
this.changeName = function(name){
this.lastname = name;
}
}
var myWorker = new Person('Adeola', 23, 'Web Developer');
myWorker.changeName('Timmy');
console.log("New Worker" + myWorker.lastname);
基本上在JS中没有类的概念,所以我们使用函数作为与现有设计模式相关的类构造函数。
//Constructor Pattern
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.doSomething = function(){
alert('I am Happy');
}
}
到目前为止,JS还不知道你想要创建一个对象,所以这里有一个新的关键字。
var person1 = new Person('Arv', 30, 'Software');
person1.name //Arv
参考:专业JS网页开发人员- Nik Z
你也可以这样做,使用结构:
function createCounter () {
var count = 0;
return {
increaseBy: function(nb) {
count += nb;
},
reset: function {
count = 0;
}
}
}
然后:
var counter1 = createCounter();
counter1.increaseBy(4);
Douglas Crockford在《The Good Parts》中广泛讨论了这个话题。他建议避免使用new操作符来创建新对象。相反,他建议创建定制的构造函数。例如:
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
在Javascript中,函数是一个对象,可以用来与new操作符一起构造对象。按照惯例,打算用作构造函数的函数以大写字母开头。你经常会看到这样的事情:
function Person() {
this.name = "John";
return this;
}
var person = new Person();
alert("name: " + person.name);**
如果在实例化新对象时忘记使用new操作符,则得到的是一个普通的函数调用,并且它绑定到全局对象,而不是绑定到新对象。