вы можете использовать FormData
$("#add_product").click(function(e){
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name",$("product_name").val());
if($("#file")[0].files.length>0)
fdata.append("file",$("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data:fdata,
contentType: false,
processData: false,
success: function(response)
{
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
One reason to invoke clone()
instead of the copy constructor or a factory method is that none of the other options may be available.
Implementing clone()
to perform a shallow object copy (deep copy is more involved) is trivial compared to implementing a copy constructor or a factory method to perform the same operation. To implement clone()
, a class need simply implement the Cloneable
interface and override method clone()
with one that invokes super.clone()
which usually invokes Object.clone()
. Object.clone()
copies every property of the original object into the corresponding property of the duplicate, thus creating a shallow copy.
Though implementing clone()
is straightforward, it is still easy to forget to implement Cloneable
. Consequently, a potential risk of using clone()
to duplicate an object is that if the class of that object does neglect to implement Cloneable
and clone()
invokes Object.clone()
either directly or indirectly, it will throw CloneNotSupportedException
.
See this code example and a previous discussion on the poor design of the Cloneable
interface.
По-видимому, они хотели копию. Возможно, они хотят передать его другой функции и не могут быть уверены, что та функция не изменит его. Это - способ удостовериться, что метод doStuff () является константой относительно состояния объекта Foo, что к этому обращаются.
Это может быть оптимизация производительности, в зависимости от того, сколько работы сделано в конструкторах.
Это более вероятно используется, потому что семантика отличается. Клонирование позволяет реализовывать "опытную семантику" (как в JavaScript, сам, и т.д.) на языке, который обычно не ухаживает за тем путем.
Если конструктор SomeObject делает дорогую работу, такую как захват чего-то от базы данных или парсинга чего-то или чтения чего-то из файла тогда, клон имел бы смысл стараться не делать работу.
, Если конструктор ничего не делает тогда, действительно нет никакой потребности использовать клон.
Редактирование: добавленный код, чтобы показать, что клон не должен делать той же работы как конструктор:
class Main
implements Cloneable
{
private final double pi;
public Main()
{
System.out.println("in Main");
// compute pi to 1,000,000,000 decimal palaces
pi = 3.14f;
}
public Object clone()
{
try
{
return (super.clone());
}
catch(final CloneNotSupportedException ex)
{
throw new Error(); // would not throw this in real code
}
}
public String toString()
{
return (Double.toString(pi));
}
public static void main(String[] args)
{
final Main a;
final Main b;
a = new Main();
b = (Main)a.clone();
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Основной construtor называют однажды, вычислительное пи выполняется однажды.